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 .