更改for循环的初始值

时间:2018-01-10 09:09:05

标签: java for-loop do-while

我正在尝试在代码中添加图书。假设有人想要添加30本书,迭代次数从0到30,这很好。如果他想在以后再增加10本书,那么它只会毫无用处,因为我需要它们从30到40开始。我该如何解决这个问题呢?

int currentBooks = 0;
do {
    System.out.print("How many books would you like to add? ");
    int nbBooks = sc.nextInt();
    // Add nbBooks amount to inventory array

    if (inventory.length-currentBooks >= nbBooks) {
        for (int w = 0; w < inventory.length; w++) {
            inventory[currentBooks] = new Book();
            currentBooks = w;
        }
        valid = true;
        break password;
    }   
    else {
        System.out.print("You can only add " + inventory.length + " books.\n");
        add = true;
    }
} while(add);

1 个答案:

答案 0 :(得分:2)

普通数组(在您的情况下为Book[])的缺点是无法更改其长度。 你应该使用List (尽管你出于某种奇怪的原因不允许你这样做。)

使用List接口

因此,最好使用List接口(以及它的实现,例如,ArrayList),它在内部使用数组,但如果需要,它会自动扩展其内部数组,所以不必担心:

// List is an interface, so we need a certain implementation of that interface
// to use. ArrayList is a good candidate:
List<Book> books = new ArrayList<>();

现在我们创建了一个ArrayList,其初始长度为0.可以使用size()方法获取长度,而不是数组的length属性。

int nbBooks = sc.nextInt();
for (int i = 0; i < nbBooks; i++) {
    books.add(new Book());
}

没有List接口

但是,如果您不能或不可以使用List界面,那么您可以选择一些选项,具体取决于您想要的内容。

其中一个选项是创建一个类,其中包含Book s,长度作为属性的数组,因为您必须将长度存储在某处< / EM>:

class BookList {

    private Book[] books = new Book[100]; // Or some maximum length
    private int size;

    public void add(Book book) {
        this.books[this.size] = book;
        this.size++;

        // You could optionally 'extend' the array with System.arraycopy
        // when the internal array exceeds 100, but I'll leave that to
        // you
    }
}

请注意,这实际上是ArrayList类的自制版本。

在您的情况下,您已在某处定义了inventory。您需要引入inventorySize或其他内容,每次添加图书时,您都会增加inventorySize变量。

Book[] inventory;
int inventorySize;

和你的方法:

...
System.out.print("How many books would you like to add? ");
int nbBooks = sc.nextInt();

for (int i = 0; i < nbBooks; i++) {
    this.inventory[this.inventorySize + i] = new Book();
}
this.inventorySize += nbBooks;

您还可以检查最后一个非null元素(或第一个null元素)并考虑数组的长度,但这将是非常糟糕的代码,因为,例如,您必须遍历数组计算它的长度,这在性能上可能相当昂贵。