Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop on Scanner.hasNext, reading from a file

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 .

like image 753
Abdullah Leghari Avatar asked Dec 19 '25 14:12

Abdullah Leghari


2 Answers

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
like image 168
NiziL Avatar answered Dec 21 '25 03:12

NiziL


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.

like image 29
Sanjeev Avatar answered Dec 21 '25 02:12

Sanjeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!