努力理解如何遍历列表

Struggling to understand how to loop over a list

我目前正在开发一个 POS 收银系统作为一项大学作业,我完全被一个 for 循环难住了,我需要实现它来保存最终用户添加到系统中的任何数据。 save() 函数用于将放入程序的任何数据保存到 2 个 .txt 文件中的 1 个(stock 或 till)。

我目前已经为每个不同的实例变量构建了保存函数,但是当它通过 save() 方法 运行 时,它只会 运行 一次(显然)并且我我很难理解如何实现循环示例作为解决方案。

这是我目前的进度:

public void save() throws IOException {
    // IMPLEMENTATION
    PrintWriter outfileStock = new PrintWriter(new FileWriter(SHOP_STOCK_DATA_FILE));
    outfileStock.println(barcode);
    outfileStock.println(cost);
    outfileStock.println(quantity);

    outfileStock.close();

    PrintWriter outfileTill = new PrintWriter(new FileWriter(SHOP_TILL_DATA_FILE));
    outfileTill.println();
    outfileTill.println();
    outfileTill.println();

    outfileTill.close();
}

我们得到的循环示例(来自导致此作业的工作表是这样的:

public void save(String fileName) throws IOException {
    PrintWriter outfile = new PrintWriter(new FileWriter(fileName));
    outfile.println(type);
    outfile.println(face);
    outfile.println(hair);
    outfile.println(powerPoints);
    outfile.println(loot.size());
    for (Treasure treasure : loot) {
        outfile.println(treasure.getName());
        outfile.println(treasure.getValue());
    }
    outfile.close();

虽然我不要求为我编写代码,但如果有人能解释

for (Treasure treasure : loot) {
    outfile.println(treasure.getName());
    outfile.println(treasure.getValue());
}

循环有效。如果需要,我可以提供更多信息,对 Java 来说还很陌生,所以不确定需要了解多少。

loot 似乎是某种列表。 for 循环将执行此列表中的每个元素,并将它们 return 作为一个名为 treasure 的对象提供给您。当你取回这个元素时,你可以把它当作一个普通的 Treasure 对象。在您的情况下,它似乎是将宝藏名称和价值写入文件。

For each loop

这是基本的 Java。变量 loot 是可以迭代的东西。它要么是一个数组,要么是像 ArrayList 这样的容器 类 之一。它包含 Treasure 对象。

对于战利品数组中的每个元素,执行这两行代码。

战利品是 List。因此,使用此 enhanced for loop 它会在每次迭代中获取每个元素并将其分配给 treasure 变量。但是在这里您无法在给定时间内访问列表的前一个元素。如果您在每次迭代中使用其他 for 循环 for(int x=0; x < size ; x++ ),您可以通过编码`loot.get(x-1) 或 loot.get(x+1) 来访问上一个或下一个元素。因此,这取决于您的要求。

loot 是一个包含 Treasure 对象 .

ArrayList
for (Treasure treasure : loot) {
    outfile.println(treasure.getName());
    outfile.println(treasure.getValue());
}

通过这行代码遍历每个 Treasure对象(每个临时分配给treasure):

for (Treasure treasure : loot) {

这意味着(对于 loot 中的每个 Treasure 对象,您称之为 treasure

并获取(每个)它们的 nametreasure.getName())和它们的值(treasure.getValue())。

:

代表在Java SE 5.0中引入的enhanced for-loop。在此处查看更多信息:

https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

基本上,而不是

for (int i=0; i < array.length; i++) {
    System.out.println("Element: " + array[i]);
}

你现在可以做

for (String element : array) {
    System.out.println("Element: " + element);
}