Scorpiorian83 Scorpiorian83 - 7 months ago 22
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

File
input
IO
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
if-else
statement and for the else part I don't understand why is it necessary.

Here's my code:

import java.io.*;
import java.util.*;

class FileReadingExercise2 {

public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
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
System.exit(0);
}

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 {
fileInput.next(); // else go to the next token
}
}
System.out.println(sum);
fileInput.close();
}
}


As you can see, as long as the fileInput
Scanner
has a next token to look up to then operate the if else statement. If fileInput has a next
Int
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! ;)

Answer
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:

1

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

Comments