Home > DeveloperSection > Forums > Java Scanner issue : Why input is skipped when using next(), nextInt() etc. after nextLine()
Mary Johnson
Mary Johnson

Total Post:3

Points:21
Posted on    October-09-2015 6:13 AM

 Java Java 
Ratings:


 1 Reply(s)
 435  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.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?




Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    October-09-2015 6:50 AM

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();

Don't want to miss updates? Please click the below button!

Follow MindStick