我正在介绍CS类,我们必须从文件中提取字符串并打印该字符串在文件中的次数。那部分工作正常。问题是我们必须循环它,以使它针对所需的任意数量的字符串进行相同的处理。当我将对字符串在文件中的次数进行计数的变量计数器重置为0时,输出显示该变量为0。它被初始化为0,所以我看不到循环后会发生什么变化。

while (answer) {
    int timesUsed = 0;  for (int i = 0; i < monAr.length; ++i) {
        while (monFile.hasNext()) {
            monAr[i] = monFile.next();

            if (monAr[i].equalsIgnoreCase(desiredTag)) {
                timesUsed = timesUsed + 1;
            }
        }
    }
    System.out.println("On Monday, #" + desiredTag + " appeared " + timesUsed + " times "+ "and was " + (((float) timesUsed / monAr.length) * 100) + "% of all hashtags used for the day.");
    System.out.print("Do you want to search another hashtag (y/n)? ");
    choice = scnr.nextLine();

    if (choice.equals("n")) {
     answer = false;
   }
}

最佳答案

您可以具有另一个变量,例如totalUses,它将存储每次迭代的结果:

int totalUses = 0;
while (answer) {
    int timesUsed = 0;
    for (int i = 0; i < monAr.length; ++i) {
        while (monFile.hasNext()) {
            monAr[i] = monFile.next();

            if (monAr[i].equalsIgnoreCase(desiredTag)) {
                timesUsed = timesUsed + 1;
            }
        }
    }
    System.out.println("On Monday, #" + desiredTag + " appeared " + timesUsed + " times "+ "and was " + (((float) timesUsed / monAr.length) * 100) + "% of all hashtags used for the day.");
    System.out.print("Do you want to search another hashtag (y/n)? ");
    choice = scnr.nextLine();

    if (choice.equals("n")) {
     answer = false;
   }
   totalUses += timesUsed;
}
System.out.println("Total uses : "+ totalUses);

09-27 00:38
查看更多