Scorpiorian83 Scorpiorian83 - 6 months ago 17x
Java Question

Why does my while loop needs this line of code to run?

I just completed an application which prompts the user for a text

but I have something to clarify as the final part,
While loop
I actually managed to refer it to a tutorial on google. In this loop, there is a
statement and for the else part I don't understand why is it necessary.

Here's my code:

import java.util.*;

class FileReadingExercise2 {

public static void main(String[] args) {
Scanner userInput = new Scanner(;
Scanner fileInput = null;

do {
try {
System.out.println("Please enter the name of a file or type QUIT to finish");
String a = userInput.nextLine();

if (a.equals("QUIT")) { // if user inputs QUIT then stop application

fileInput = new Scanner(new File(a)); // the file contains text and integers
} catch (FileNotFoundException e) {
System.out.println("Error - File not found");
} while (fileInput == null);

int sum = 0;

while (fileInput.hasNext()) // continues loop as long as there is a next token
if (fileInput.hasNextInt()) // if there is an int on the next token
sum += fileInput.nextInt(); // then adds the int to the sum
} else {; // else go to the next token

As you can see, as long as the fileInput
has a next token to look up to then operate the if else statement. If fileInput has a next
then adds it up to the sum variable. So from what I think is that this will be sufficient. Once fileInput has no more token to read, it shall get out of the
while loop
isn't it? Why does it has still go onto the next token? I'm confused. Please advise thanks! ;)

Why does it has still go onto the next token?

That is because when nextInt() is executed it will consume the int number within the file but within it, it has a newLine character that needs to be consume and that is when next is executed to consume that newLine after the int number.

sample file content:


what actually in there is 1 character and newline \n character