简体   繁体   中英

Loop iterates through array too many times Java

so I am working on a java project that will order Items. However in my code, which is supposed to iterate through some tokenized terms and assign them to values in a custom Items class seems to not be working.
Code:

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

Item Class:

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

When I run though the tokenize terms method and print the values of each item in itemArray I get a set of items that look like this.
Name: Book Quantity: 14 Price: 856.89
Name: Book Quantity: 14 Price: 856.89
Name: Book Quantity: 14 Price: 856.89
However I know this should not be happening since the String[] tokenizedTerms looks like this:

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

The problem is with your initialization of the array. You put multiple references to the same Item instance in your array :

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

You should put different Item instances in each index of the array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM