苦苦挣扎,了解如何循环列表

时间:2015-03-12 17:47:22

标签: java loops for-loop

我目前正在开发一个POS系统作为大学任务,我完全被我需要实现的for循环所困,以保存最终用户添加到系统中的任何数据。 save()函数用于将放入程序的任何数据保存为2个.txt文件中的1个(库存或直到)。

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

这是我目前的进展:

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,所以不确定需要多少才能理解。

4 个答案:

答案 0 :(得分:1)

战利品似乎是某种类型的清单。 for循环将做的是获取此列表中的每个元素,并将它们作为名为treasure的单个对象返回给您。当你得到这个元素时,你可以将它视为一个普通的Treasure对象。在你的情况下,它似乎是将宝藏名称和价值写入文件。

For each loop

答案 1 :(得分:1)

lootArrayList,其中包含Treasure 个对象

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

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

for (Treasure treasure : loot) {

表示(对于您Treasureloot treasure中的每个name对象

并获取(每个)treasure.getName()treasure.getValue())及其值(: )。

enhanced for-loop

代表Java SE 5.0中引入的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);
}

你现在可以做到

{{1}}

答案 2 :(得分:0)

这是基本的Java。变量战略是可以迭代的东西。它可以是数组,也可以是ArrayList之类的容器类。它包含Treasure对象。

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

答案 3 :(得分:0)

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