forum

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

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

Anonymous User 1886 09-Oct-2015
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?



Updated on 09-Oct-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By