Infinite loop on Scanner.hasNext, reading from a file

流过昼夜 提交于 2019-12-31 02:54:12

问题


I'm apparently facing an infinite loop on while(input.hasNext()) , as in following code

File file = new File("data.txt");
Scanner input = new Scanner(file);

int sum = 0;

while (input.hasNext()) {
    if (input.hasNextInt()) {
        sum += input.nextInt();
    }
}
System.out.println(sum);

Some related questions explain why it always returns true if input stream is System.in, however I'm scanning through a File.

Please let me know where I'm going wrong.

I'm attempting to calculate the sum of unique integer values (space delimited where they occur).

Edit:

Lesson learned, input.hasNext() does not move the pointer to the next line and thus the scanner does not advance past any input. As explained in answers to this question as well as here .


回答1:


Well, according to

while(input.hasNext()) {
  if(input.hasNextInt()) {
    sum += input.nextInt();
  }
}

Your scanner will not consume the next token if this token isn't an int, you can hilight this behavior with something like

int k=0;
while(input.hasNext()) {
  if(input.hasNextInt()) {
    sum += input.nextInt();
  } else {
    System.err.println("What ? It's not an integer...");
    if ( k < 1 ) {
      System.err.println("I'm gonna try again !");
      k++;
    } else {
      System.err.println("'"+input.next()+"' it's definitively not an integer");
      k=0;
    }
  }
}

Finally, there are many solutions, for example :

  • Modify your input file the remove all the non-integer token
  • Consume the non-integer token with Scanner::next()
  • Sanjeev's answer



回答2:


You do not need to double checking on content. this should work:

   File file = new File("data.txt");
    Scanner input = new Scanner(file);

    int sum = 0;

    while(input.hasNextInt()) {
            sum += input.nextInt();
    }
    System.out.println(sum);

Hope this helps.




回答3:


Seems like scanner is reading a non int value from your file and when it does , while(input.hasNext()) will always be true because there is something as an input to scanner but it is not int. So scanner skips reading this non-int value in the inner if(input.hasNextInt()) check.

So scanner does not proceed beyond this element and always return true.

If you want to sum up all the integers in your file then you should modify your code to below:

while(input.hasNext()) {            
            if(input.hasNextInt()) {                
                sum += input.nextInt();
            }
            else
                input.next();
        }

Just read the non integer elements when scanner encouters it. Hope this clarifies.



来源:https://stackoverflow.com/questions/23676834/infinite-loop-on-scanner-hasnext-reading-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!