java - 循环遍历数组太多次Java

标签 java arrays loops for-loop

所以我正在开发一个将订购商品的 Java 项目。然而,在我的代码中,应该遍历一些标记化的术语并将它们分配给自定义 Items 类中的值似乎不起作用。
代码:

public void tokenizeTerms(String content) {
        String[] tokenizedTerms = content.split(" ");
        Item[] itemArray = new Item[tokenizedTerms.length/3];
        Item fillItem = new Item();
        fillItem.setName("fillItem");
        fillItem.setPrice(0.00);
        fillItem.setQuantity(1);
        Arrays.fill(itemArray, fillItem);
        int currToken = 0;
        for(int i = 0; i < itemArray.length; i++) {
            itemArray[i].setName(tokenizedTerms[currToken]);
            currToken++;
            try {
                int foo = Integer.parseInt(tokenizedTerms[currToken]);
                itemArray[i].setQuantity(foo);
                currToken++;
                double moo = Double.parseDouble(tokenizedTerms[currToken]);
                itemArray[i].setPrice(moo);
                currToken++;
            } catch (Exception e) {
                System.out.println("Error parsing data.");
            }

        }
        this.items = itemArray;
    }

元素等级:

public class Item {
    private String name;
    private int quantity;
    private double price;

    public void setName (String name) {
        this.name = name;
    }
    public String getName () {
        return this.name;
    }
    public void setQuantity (int quantity) {
        this.quantity = quantity;
    }
    public int getQuantity () {
        return this.quantity;
    }
    public void setPrice (double price) {
        this.price = price;
    }
    public double getPrice () {
        return this.price;
    }
}

当我运行 tokenize terms 方法并打印 itemArray 中每个项目的值时,我得到一组看起来像这样的项目。
名称:图书数量:14册价格:856.89
名称:图书数量:14册价格:856.89
名称:图书数量:14册价格:856.89
但是我知道这不应该发生,因为 String[] tokenizedTerms 看起来像这样:

[CD, 32, 459.2, T-Shirt, 22, 650.8, Book, 14, 856.89]

最佳答案

问题出在数组的初始化上。您在数组中放置了对同一个 Item 实例的多个引用:

    Item fillItem = new Item();
    ...
    Arrays.fill(itemArray, fillItem);

你应该在数组的每个索引中放置不同的 Item 实例:

for(int i = 0; i < itemArray.length; i++) {
    itemArray[i] = new Item ();
}

关于java - 循环遍历数组太多次Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227327/

相关文章:

javascript - 从 JSON 响应生成数组组合

c - 并行运行两个程序,每个程序都有无限循环

python - 总结 Pandas 表中的循环结果

java - eclipse 用感叹号标记每个新项目

java - 如何使用 Libgdx 和 Intellij Idea 在多台计算机上进行开发

c++ - Visual Studio 错误。它在 CodeBlocks 中工作...要求 const

php - 使用 PHP 获取名称和值

java - 通过自定义类在javafx中添加事件处理程序

java - ECB 模式下的 RSA 加密

JavaScript:函数在循环时给出 "is not a function"