JAVA SCANNER ISSUE : WHY INPUT IS SKIPPED WHEN USING NEXT(), NEXTINT() ETC. AFTER NEXTLINE()

Mary Johnson

Total Post:3

Points:21
Posted by  Mary Johnson
Java 
 846  View(s)
Ratings:
Rate this:
I am working on a small java implementation, but  i am astonished  when i saw a weird behavior of scanner class methods, If i need to take two inputs  : first one integer value and next a String. So i used nextInt() first for integer and then nextLine() for string :
import java.util.Scanner;


public class ScannerIssue {

public static void main(String[] args){

Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer");
int i = sc.nextInt();
System.out.println("Enter a String");
String j = sc.nextLine();
System.out.println(i);
System.out.println(j);
sc.close();


}
}
Now the output is 
Enter an integer
6
Enter a String
6
i.e it skipped the input from nextLine() method and only prompting input once for integer and print its value 
What is going wrong in this code?


  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Java Scanner issue : Why input is skipped when using next(), nextInt() etc. after nextLine()

    Hi Mary,


    I think its kind of a unnoticeable bug in scanner class, here the scanner's nextInt() method doesn't consumes the last newline character of the input , which is then consumed in the next call to scanner nextLine() method.

    We can handle this by  calling a blank nextLine() after nextInt() to consume the left over new line chaacter
    int option = input.nextInt();
    input.nextLine();  // Consume newline left-over
    String str1 = input.nextLine();
    We can also do this, by taking both the inputs as String by calling nextLine() method and convert the integer value using Integer.parseInt(string) method. For this we need to use try-catch block coz Integer.parseInt throws NumberFormatException when an invalid argument pass through it. 

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!