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

Total Post:3

 1286  View(s)
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.out.println("Enter an integer");
int i = sc.nextInt();
System.out.println("Enter a String");
String j = sc.nextLine();

Now the output is 
Enter an integer
Enter a String
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. Post:397

    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) {
    String str1 = input.nextLine();