title: Using scanner.nextLine()
body: <p>I have been having trouble while attempting to use the nextLine() method from java.util.Scanner. </p>
  
  <p>Here is what I tried:</p>
  
  <pre><code>import java.util.Scanner;
  
  class TestRevised {
      public void menu() {
          Scanner scanner = new Scanner(System.in);
  
          System.out.print("Enter a sentence:\t");
          String sentence = scanner.nextLine();
  
          System.out.print("Enter an index:\t");
          int index = scanner.nextInt();
  
          System.out.println("\nYour sentence:\t" + sentence);
          System.out.println("Your index:\t" + index);
      }
  }
  </code></pre>
  
  <p><strong>Example #1:</strong> This example works as intended. The line <code>String sentence = scanner.nextLine();</code> waits for input to be entered before continuing on to <code>System.out.print("Enter an index:\t");</code>.</p>
  
  <p>This produces the output:</p>
  
  <pre><code>Enter a sentence:   Hello.
  Enter an index: 0
  
  Your sentence:  Hello.
  Your index: 0
  </code></pre>
  
  <hr>
  
  <pre><code>// Example #2
  import java.util.Scanner;
  
  class Test {
      public void menu() {
          Scanner scanner = new Scanner(System.in);
  
          while (true) {
              System.out.println("\nMenu Options\n");
              System.out.println("(1) - do this");
              System.out.println("(2) - quit");
  
              System.out.print("Please enter your selection:\t");
              int selection = scanner.nextInt();
  
              if (selection == 1) {
                  System.out.print("Enter a sentence:\t");
                  String sentence = scanner.nextLine();
  
                  System.out.print("Enter an index:\t");
                  int index = scanner.nextInt();
  
                  System.out.println("\nYour sentence:\t" + sentence);
                  System.out.println("Your index:\t" + index);
              }
              else if (selection == 2) {
                  break;
              }
          }
      }
  }
  </code></pre>
  
  <p><strong>Example #2:</strong> This example does not work as intended. This example uses a while loop and and if - else structure to allow the user to choose what to do. Once the program gets to <code>String sentence = scanner.nextLine();</code>, it does not wait for input but instead executes the line <code>System.out.print("Enter an index:\t");</code>.</p>
  
  <p>This produces the output:</p>
  
  <pre><code>Menu Options
  
  (1) - do this
  (2) - quit
  
  Please enter your selection:    1
  Enter a sentence:   Enter an index: 
  </code></pre>
  
  <p>Which makes it impossible to enter a sentence.</p>
  
  <hr>
  
  <p>Why does example #2 not work as intended? The only difference between Ex. 1 and 2 is that Ex. 2 has a while loop and an if-else structure. I don't understand why this affects the behavior of scanner.nextInt(). </p>