Ankit Rathore Ankit Rathore - 1 month ago 8
Java Question

error in taking input string after integer in java

I was trying to do this :

int n = myScanner.nextInt();
for(int i=0;i<n;i++){
String str = myScanner.nextLine();
.
.
.
}


when i compiled it shows some errors java.util.Scanner.nextInt(Scanner.java:2117).
initially i thought it is a problem of nextLine() so i used next() . then i found out if i add myScanner.nextLine() after taking input in n i.e

int n = myScanner.nextInt();
myScanner.nextLine();


Then it worked fine. I want to know why this happened?

Answer

You need to consume the newline character you enter when passing the integer:

int n = myScanner.nextInt(); //gets only integers, no newline
myScanner.nextLine(); //reads the newline
String str;
for(int i=0;i<n;i++){
   str = myScanner.nextLine(); //reads the next input with newline
   .
   .
   .
}
Comments