title: Why does my while loop needs this line of code to run?
body: <p>I just completed an application which prompts the user for a text <code>File</code> input <code>IO</code> but I have something to clarify as the final part, <code>While loop</code> I actually managed to refer it to a tutorial on google. In this loop, there is a <code>if-else</code> statement and for the else part I don't understand why is it necessary.</p>
  
  <p>Here's my code:</p>
  
  <pre><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();
      }
  }
  </code></pre>
  
  <p>As you can see, as long as the <strong>fileInput</strong> <code>Scanner</code> has a next token to look up to then operate the if else statement. If <strong>fileInput</strong> has a next <code>Int</code> then adds it up to the <strong>sum</strong> variable. So from what I think is that this will be sufficient. Once <strong>fileInput</strong> has no more token to read, it shall get out of the <code>while loop</code> isn't it? Why does it has still go onto the next token? I'm confused. Please advise thanks! ;)</p>