我无法使用增强型 for 循环让产品对象打印出任何内容。一切都为空或 0?
输出显示这个?
0null0.0This is the id
0null0.0This is the id
0null0.0This is the id
这是我的代码:
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
ArrayList < Product > store1 = new ArrayList < Product > ();
store1.add(new Product(3, "Nike", 300.0));
store1.add(new Product(2, "Addidas", 400.0));
store1.add(new Product(6, "Under Armor", 500.0));
for (Product y: store1) {
System.out.println(y + "This is the id");
}
}
}
class Product {
public int id;
public String name;
public double price;
public Product(int startId, String startName, double startPrice) {
startId = id;
startName = name;
startPrice = price;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public String toString() {
return id + name + price;
}
}
最佳答案
您正在构造函数中进行向后赋值:
public Product(int startId, String startName, double startPrice) {
startId = id;
startName = name;
price = startPrice;
}
让对象未初始化...
但你的意思是肯定的
public Product(int startId, String startName, double startPrice) {
id = startId;
name = startName;
startPrice = price;
}
关于java - 使用增强的 For 循环在 ArrayList 中打印对象时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710474/