Getting user input | Sololearn: Learn to code for FREE!

0

Getting user input

I've been trying to get to input from 5 user, but after the first print out the, the program skips the print statemen that request for the second users name. Here is the code below. import java.util.Scanner; public class Employeepayroll { public static void main(String[] args) { Scanner sc= new Scanner(System.in); for(int i=0;i<5;i++){ System.out.println("Enter Fullname: "); sc.nextLine(); System.out.println("Enter your total working hour for the week: "); sc.nextInt(); if(sc.hasnext()){ sc.nextLine(); } } }

10/1/2021 9:52:57 PM

Emmanuel Baffoe Appiah-ofori

10 Answers

New Answer

+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

+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(); }

+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.

+1

ChaoticDawg thanks man, I always thought it was because of nextLine

+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?

0

0

Is there a way to display it in a table

0

yes there is, you can create a user class, and a users list

0

So now there is a new problem

0

After adding if(sc.hasnext()){ sc.nextLine(); The scan statement was only able to take the first name and the working hour, any more then the first name will cause an error