Reputation: 641
I want to get two string inputs into a string array
String[] b = new String[n];
by using scanner but the scanner automatically takes blank value in
b[0]
.i.e. it skips the first loop.
Scanner scn = new Scanner(System.in);
int no = 0;
int n = scn.nextInt();
String[] b = new String[n];
for (int j = 0; j < n; j++) {
System.out.println("Enter the string");
b[j] = scn.nextLine();
}
the output occurs like
2
Enter
Enter
abc
can anyone suggest me why this problem occurs??
Upvotes: 1
Views: 202
Reputation: 1469
This is because nextInt()
does not read the \n
in your input. This is then read by your nextLine()
More explanation,
When you enter a number when prompted by the nextInt()
call. You type a number and press Enter This makes your input look like this
10
\n
nextInt()
reads only the 10
and leaves out \n
.
Then, your nextLine()
reads only the \n
.
This explains your output.
You can get the expected output by having an extra nextLine()
after the nextInt()
.
See this for more information on it.
Upvotes: 2