Ich habe zwei Klassen RoomDimension & RoomCarpet. Dann habe ich ein Programm, das diese beiden Klassen aufruft, aber ich habe ein Problem mit der RoomCarpet-Klasse, wenn ich versuche, ein TotalCost für den Teppich zu bekommen. Es gibt mir diesen Fehler, wenn ich laufen CarpetCalculatorNicht in der Lage Daten von einer Klasse in einer anderen mit * .get * zu bekommen()
(Exception in thread "main" java.lang.NullPointerException
at RoomCarpet.getTotalCost(RoomCarpet.java:49)
at CarpetCalculator.main(CarpetCalculator.java:44)
java: 44, dieser Ort der System.out.print am Ende ist, der die getTotalCost nennt,
, wenn ich versuche und Call die getTotalCost unter der RoomCarpet-Klasse. Ich denke, es hat mit der size.getArea() zu tun (wenn ich es anrufe). Unten ist der Code für alle Klassen. Vielen Dank für die Hilfe.
RoomDimension:
public class RoomDimension {
private double length;
private double width;
public RoomDimension(double len, double w){
length = len;
width = w;
}
public void setLength(double len){
length = len;
}
public void setWidth(double w){
width = w;
}
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public double getArea(){
return length * width;
}
public String toString(){
String str = "The length you entered was " + length
+ " and the width you entered was " + width;
return str;
}
}
RoomCarpet:
public class RoomCarpet{
private RoomDimension size;
private double carpetCost;
public RoomCarpet (double cost){
carpetCost = cost;
}
public void setCarpetCost(double cost){
carpetCost = cost;
}
public double getCarpetCost(){
return carpetCost;
}
public double getTotalCost(){
return size.getArea() * carpetCost;
}
public String toString(){
String str = "\nYour total area for your room is " + size.getArea()
+ "\nThe cost of your carpet per square foot is " + carpetCost;
return str;
}
}
CarpetCalculator:
import java.util.Scanner; // Needed for the Scanner class
/**
* This program demonstrates the RoomDimension & RoomCarpet classes.
*/
public class CarpetCalculator {
public static void main(String[] args){
double length; // hold room length
double width; // hold room width
double cost; // hold carpet cost
Scanner keyboard = new Scanner(System.in);
System.out.print("What is your rooms length? ");
length = keyboard.nextDouble();
System.out.print("What is your rooms width? ");
width = keyboard.nextDouble();
System.out.print("What is the cost of your carpet per square foot? ");
cost = keyboard.nextDouble();
RoomDimension testDimension = new RoomDimension(length, width);
RoomCarpet testCarpet = new RoomCarpet(cost);
System.out.println(testDimension);
System.out.println(testCarpet);
System.out.println("Which means your total cost to carpet the room is " + testCarpet.getTotalCost());
}
}
Thank you so viel, dass es behoben. – Naro