【发布时间】:2015-12-05 16:16:51
【问题描述】:
这是主要的 java 类,非常简单,只需询问用户房间的宽度和长度以及每平方米的价格。然后它应该显示房间的面积和总成本。
package exercise;
import javax.swing.JOptionPane;
public class carpetshopping {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input;
double width;
double length;
double price;
input = JOptionPane.showInputDialog("Please enter the width of the room");
width = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Please enter the length of the room");
length = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What about the price per unit area?");
price = Double.parseDouble(input);
RoomDimension dim = new RoomDimension(length, width);
System.out.println(dim);
RoomCarpet car = new RoomCarpet(dim, price);
System.out.println(car);
}
}
这里是RoomDimension.java,它有两个字段:length和width(都是double),它们会得到一个房间的尺寸并计算房间的面积。
package exercise;
public class RoomDimension {
public double length;
public double width;
public RoomDimension(double len, double w) {
// TODO Auto-generated constructor stub
length = len;
width = w;
}
public RoomDimension(RoomDimension size) {
// TODO Auto-generated constructor stub
length = size.length;
width = size.width;
}
public double getArea() {
return length * width;
}
public String toString() {
return "The area of this room is " + this.getArea();
}
}
这里是RoomCarpet.java,它有两个字段,一个是价格,另一个是RoomDimension.java中的一个对象,它会计算房间的总成本。
package exercise;
public class RoomCarpet {
public RoomDimension room;
public double carpetCost;
public RoomCarpet(RoomDimension room1, double carpetCost) {
// TODO Auto-generated constructor stub
room = new RoomDimension(room1);
carpetCost = carpetCost;
}
public double getTotalCost() {
return room.getArea() * carpetCost;
}
public String toString() {
return "The total cost is " + this.getTotalCost();
}
}
我的问题是:无论用户输入什么价格,总成本总是 0.0 有人帮我吗? Java 的新手,一百万谢谢!
【问题讨论】:
-
dim 和 car 打印出什么?
-
如答案所述,您在构造函数参数隐藏实例变量时遇到问题。看看
this:stackoverflow.com/questions/9967437/…
标签: java