Java 使用增强的For循环打印ArrayList中的对象时出现问题
我无法让产品对象使用增强的for循环打印任何内容。所有结果都为空或0 输出显示了这一点吗Java 使用增强的For循环打印ArrayList中的对象时出现问题,java,object,arraylist,Java,Object,Arraylist,我无法让产品对象使用增强的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 < Pr
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;
}
}
主类{
公共静态void main(字符串[]args){
System.out.println(“你好,世界!”);
ArrayListstore1=新的ArrayList();
store1.添加(新产品(3,“Nike”,300.0));
store1.添加(新产品(2,“Addidas”,400.0));
存储1.添加(新产品(6,“装甲下”,500.0));
对于(产品y:store1){
System.out.println(y+“这是id”);
}
}
}
类产品{
公共int id;
公共字符串名称;
公开双价;
公共产品(int startId、字符串startName、双startPrice){
startId=id;
startName=名称;
startPrice=价格;
}
公共int getId(){
返回id;
}
公开双价{
退货价格;
}
公共字符串getName(){
返回名称;
}
公共字符串toString(){
返回id+名称+价格;
}
}
您正在构造函数中执行反向赋值:
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;
}
您在构造函数中向后分配了任务。应该是:
public Product(int startId, String startName, double startPrice) {
id = startId; // Not `startId = id;`
name = startName; // Not `startName = name;`
price = startPrice; // Not `price = startPrice;`
}
或者更好的是(当您尝试编译时,这会为您指出问题),不要依赖隐式this
:
public Product(int startId, String startName, double startPrice) {
this.id = startId;
this.name = startName;
this.price = startPrice;
}
您在构造函数中设置变量的方式是错误的,即
startId=id代码>应该是id=startId代码>
您还应该将@Override
添加到toString()
方法中。这里是主要内容:嗨!当你问你的问题时,在文本区的右边有一个“如何设置格式”框,里面有有用的信息。还有一个工具栏,上面满是格式辅助工具。还有一个[?]按钮提供格式化帮助。还有一个预览区,显示你的帖子发布时的样子,位于文本区和“发布你的问题”按钮之间(这样你就必须滚动过去才能找到按钮,以鼓励你查看)。让你的帖子清晰明了,并证明你花了时间这样做,可以提高你获得好答案的机会。请使用“编辑”链接来改进问题。不要在评论中发布代码。请回答你的问题,不要在评论中粘贴代码,正如你所看到的那样,这会很混乱。我这次已经为你把代码放在了问题中。是的。就是这样!!!非常感谢。我把实例变量赋值搞砸了!