0
Why Scanner.nextLine() reads new line and skips one iteration when used in loop?
Description in code block. https://code.sololearn.com/c04g87FrrZkn/?ref=app
12 ответов
+ 3
Try to see if this discussion help you https://www.sololearn.com/Discuss/1516044/
+ 10
You are using Scanner after loop iteration !?
// Enter an integer:
int count = scanner.nextInt();
scanner.nextLine(); // <--
String test = scanner.nextLine();
for (int i=0; i < count; i ++){
System.out.println("Input"+(i+1));
}
where is output:
System.out.println(test); // !?
+ 8
Elvin Shrestha
Yes, you did it well,👍
I forgot that you can use Integer.parseInt() 😆, but you asked for an explanation, so I concentrated on it! 😉
You are welcome! 😊
+ 7
Elvin Shrestha
Take a look at the answer from sir John Wells, on this post,
I hope, should help you to understand!👍
https://www.sololearn.com/Discuss/1583958/?ref=app
+ 7
Elvin Shrestha
nextInt() doesn't read the new line after the counter, so nextLine() reads that one!
+ 4
Elvin Shrestha
I'm sorry, I really don't understand what you want!
Your code gives an exception!
+ 3
KrOW I've solved my problem. I used
int count = Integer.parseInt(scanner.nextLine());
instead of using nextLine() solely.
Thank you! Appreciate your time.
+ 3
Danijel Ivanović Yeah, I actually asked for the explanation. Appreciate your time. Thanks!
+ 2
Danijel Ivanović I was trying to use for loop to store multiple strings, so I've used
String test = scanner.nextLine()
inside the loop. Used String variable instead of String array because I was just trying to test the scanner. Also, same about the output, not needed.
For first iteration, that is for i = 0,
String test = scanner.nextLine() reads new line // test == \n
and forwards into next iteration (i==1), so for count = 5, I can input 4 strings only instead of 5.
int count = scanner.nextInt();
scanner.nextLine(); does the job, as this line takes care of new line.
But I'm still confused, from where the new line comes after nextInt() is executed?
Edit:
Cleared my confusion about the new line. Thank you!
+ 2
KrOW Had a hard time understanding, but it surely helped. Thank you so much!
+ 2
Elvin Shrestha Have you solved or you have yet some problems? If you dont understand something ask 😉
+ 2
Danijel Ivanović Sir John Wells answer did help, also your final answer too. Thank you so much! Sorry about that exception, you must provide some input as per the count to avoid that otherwise it throws one.