跟踪字符串在文件中出现的时间';在Java中,在循环之后无法工作

跟踪字符串在文件中出现的时间';在Java中,在循环之后无法工作,java,loops,counter,Java,Loops,Counter,我在一个CS的入门课上,我必须从一个文件中提取字符串,并打印该字符串在文件中的次数。那部分很好用。问题是我们必须循环它,让它对任意多的字符串执行相同的过程。当我将计算字符串在文件中的次数的变量计数器重置为0时,输出表示该变量为0。它在0处初始化,因此我看不到循环后有什么变化 while (answer) { int timesUsed = 0; for (int i = 0; i < monAr.length; ++i) { while (monFile.hasN

我在一个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;
   }
}
while(答案){
int timesUsed=0;用于(int i=0;i
您可以使用另一个变量,例如将存储每次迭代结果的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);
inttotaluses=0;
while(回答){
int timesUsed=0;
对于(int i=0;i
问题是您正在使用
扫描仪读取文件,但如果需要重新扫描,指针已经在文件的末尾

您需要在循环开始时在
的正下方实例化扫描仪:

Scanner monFile;
While(answer) {
    monFile = new Scanner(new File(“test/Monday”));
    ...
}

什么是
monFile
?似乎需要重置该变量的读取器。可能是在
行下方实例化了该变量,而
行下面我不确定是否应该添加该代码。monFile是与周一存储的文件相关的变量(一周中的每一天都有一个),它是Scanner monFile=new Scanner(new file(“test/Monday”);它通过在while(答案)行的正下方添加该行来实现感谢YOUTry