Infinite loop on Scanner.hasNext, reading from a file

后端 未结 3 1486
野的像风
野的像风 2021-01-22 17:32

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

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


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 17:45

    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

提交回复
热议问题