Java Arrays [] - 将For循环中的特定元素分配给某些值

时间:2014-11-24 11:39:16

标签: java arrays bluej

我试图为BlueJ(Java)中的程序编写一些代码,这些程序列出了包,并添加和删除这些包中的项目,这类事情。然后我陷入了第一堂课;我无法正确地将一个项目添加到包中,因为您可以在addItem()方法中注意到这一点;它继续将String s添加到数组中的每个null元素,而不是第一个遇到的。任何帮助都将受到极大的赞赏。

祝福&非常感谢,

的Xenos

public class Bag1 {
    private String[] store; // This is an array holding mutlitple strings.

    public Bag1(int storageCapacity) {
        store = new String[storageCapacity];
    } // That was the primitive array constructor.

    public boolean isFull() {
        boolean full = true;
        for(int i = 0; i < store.length; i++) {
            if(store[i] == null) {
                full = false;
            }
        }
        return full;
    } // The method above checks if the bag is full or not, and returns a boolean value on that basis.

    public void add(String s) {
        for(int i = store.length; i >= 0; i--) {
            if(store[i] == null) {
                store[i] = s;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你应该在找到第一个空位后退出循环:

public void add(String s) 
{
    for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
        if(store[i]==null) {
            store[i] = s;
            break;
        }
    } 
}