Java中的[a bug]按引用传递
这里是主要的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);
}
}
这是房间的尺寸。在java中,它有两个字段:长度和宽度(都是双字段),这两个字段将获得房间的尺寸并计算房间面积
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();
}
}
这是房间的地毯。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的新宝贝,万分感谢
# 1 楼答案
问题出在
RoomCarpet
类中。在构造器中,使用相同的变量carpetCost = carpetCost
会混淆JVM,这会导致实例变量隐藏。编译器会感到困惑,无法为成本变量指定正确的值你的改良地毯课:
# 2 楼答案
你的问题在你的RoomHeart类中,在要指定的构造函数中
你在写
这里的问题是,编译器两次都使用参数变量来表示“地毯成本”,所以基本上是将变量分配给它自己,甚至不触及要更改的实例变量
要解决此问题,请使用“this”引用实例变量:
为了避免将来出现这种情况,只需习惯通过“this”引用实例变量即可因为编译器知道你说的是哪个变量
顺便说一下。。。如果您还没有使用eclipse(我认为这是因为您的问题),我强烈建议您使用它。我花了大约一秒钟的时间才在代码中找到问题,因为eclipse已经为我标记了有问题的部分,并告诉我它可能有问题;)
你好,瑞文