【问题标题】:Trouble printing objects in ArrayList using Enhanced For Loop使用增强型 For 循环在 ArrayList 中打印对象时遇到问题
【发布时间】:2019-09-06 16:37:05
【问题描述】:

我无法让产品对象使用增强的 for 循环打印出任何内容。一切都是 null 还是 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;
    }
}

【问题讨论】:

  • 这里是主要的:
  • 嗨!当您提出问题时,文本区域右侧有一个 如何格式化 框,其中包含有用的信息。还有一个工具栏,里面装满了格式化辅助工具。还有一个 [?] 按钮提供格式化帮助。 一个预览区域,显示您的帖子在发布时的样子,位于文本区域和“发布您的问题”按钮之间(这样您就必须滚动过去才能找到该按钮,以鼓励你看它)。使您的帖子清晰,并证明您花时间这样做,可以提高您获得好答案的机会。
  • 请使用“编辑”链接改进问题。不要在 cmets 中发布代码。
  • edit您的问题,不要将代码粘贴到您看到的cmets中,它会变得混乱
  • 这次我已将代码放入问题中。

标签: java object arraylist


【解决方案1】:

您正在构造函数中进行反向分配:

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;
    }

【讨论】:

  • 是的。就是这样!!!非常感谢。我搞砸了我的实例变量赋值!
【解决方案2】:

您在构造函数中向后分配了任务。应该是:

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;
}

【讨论】:

    【解决方案3】:

    您在构造函数中以错误的方式设置变量,即

    startId = id; 应该是id = startId;

    您还应该将@Override 添加到您的toString() 方法中。

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2023-03-06
      • 2012-04-06
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多