Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8350190

Scanner:nextLine() skips input after nextInt() due to leftover newline character

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      In Java, when using the Scanner class to read input with methods like nextInt(), nextDouble(), next(), etc., the newline character (\n) generated when the user presses Enter is not consumed. This leftover newline character causes issues when calling nextLine() immediately after one of these methods, as nextLine() consumes the newline character and immediately returns with an empty string, skipping the intended input prompt.

      Steps to Reproduce:
      -> Use methods like nextInt(), next(), nextDouble(), etc., to read input.
      -> Call nextLine() immediately after to read a string input.
      -> Notice that nextLine() is skipped, as it consumes the leftover newline character from the previous input method.

      Expected Behavior:
      After reading input with methods like nextInt(), next() or nextDouble(), the program should automatically consume the newline character (\n) without requiring developers to manually call nextLine(). This would ensure that subsequent calls to nextLine() behave as expected, allowing for proper input without skipping.

      Actual Behavior:
      The nextLine() method immediately consumes the leftover newline character from the previous input method, causing it to skip the string input prompt and return an empty string.

      Suggested Solution:
      The Scanner class could automatically consume the newline character after reading an input with methods like nextInt(), next(), nextDouble(), etc., without requiring developers to explicitly handle this. This would simplify code and prevent the need for additional calls to nextLine() in between input methods.



       

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: