Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
This error is caused by SC.nextLine() In the first interaction, the name and hours are read, but in the second and in the remaining interactions, the nextLine skips reading to the next. Replace nextLine with next or create a function to read data using nextLine
1st Oct 2021, 10:09 PM
Erlénio.RS
Erlénio.RS - avatar
+ 3
It's actually not due to the use of sc.nextLine(), but rather sc.nextInt() that causes the issue. This is due to sc.nextInt() leaving the trailing newline character '\n' in the input stream. So on the next iteration of the loop sc.nextLine() catches this character '\n' and then causes an error when sc.nextInt() attempts to take in the String that was intended to be caught by the previous sc.nextLine(). 1. In your for loop change the condition to < instead of <= if you only intend to iterate the loop 5 times. 2. Add the following code after sc.nextInt() to capture the remaining '\n' character that is left in the stream. if(sc.hasNext()) { sc.nextLine(); }
1st Oct 2021, 10:22 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Erlénio.RS I guess in a way it's more the use of the 2 different type of methods in conjunction with each other. Most the Scanner.next**() methods only consume up to the 1st whitespace character (after non-whitespace), where nextLine() will consume up to the 1st newline character. So, when the former is used prior to the latter, the newline character remaining in the input stream causes an issue. In this case, due to it being a loop, it is used after the 1st call to nextLine(), but prior to the successive calls.
1st Oct 2021, 10:42 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg thanks man, I always thought it was because of nextLine
1st Oct 2021, 10:28 PM
Erlénio.RS
Erlénio.RS - avatar
+ 1
Emmanuel Baffoe Appiah-ofori Please post your updated code. Did you change anything else in your code prior to making the changes I recommend? If so, try changing them back and only use the changes I suggested. Did you change the condition, as suggested as well?
1st Oct 2021, 10:47 PM
ChaoticDawg
ChaoticDawg - avatar
0
yes there is, you can create a user class, and a users list
1st Oct 2021, 10:21 PM
Erlénio.RS
Erlénio.RS - avatar