-1

I am creating a Register Employee Menu.

If there is a space on the String variables, then the scanner passes one line ahead, for no reason.

Output and input results

Code

System.out.println("===========MENU REGISTER EMPLOYEE=============\n");
System.out.println("Enter data that is being asked\n");
System.out.println("Employee ID:\n");
readerEmployeeID = sc.nextInt();
System.out.println("Role ID:\n");
readerRoleID = sc.nextInt();
System.out.println("Name:\n");
readerName = sc.next();
System.out.println("Address:\n");
readerAddress = sc.next();
System.out.println("PhoneNumber:\n");
readerPhoneNumber = sc.nextInt();
System.out.println("Email:\n");
readerEmail = sc.next();
System.out.println("SOC:\n");
readerSoc = sc.nextInt();

Attempts to solve

I already tried:

  • nextLine()
  • next()
  • next().trim()
  • nextLine().trim()

But it still passes one line ahead.

Why is this happening?

hc_dev
  • 2,428
  • 15
  • 20
  • 1
    please remove ``"\n"`` from the message. ```System.out.println``` already adds a new line. – pratap May 08 '21 at 13:47
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the full source code you have as a [mcve], which can be compiled and tested by others. – Progman May 08 '21 at 13:50
  • `next()` reads up to a delimiter. So the first call to `next()` will read the Name "a" and the second call to `next()` doesn't need to wait for input since there's already another "a" in the pipe, which will be assigned to `readerAddress`. – Sotirios Delimanolis May 08 '21 at 13:55
  • Hi guys! The way to resolve this problem is to put this sc.nextLine(); after the scanner reads the string. The other ways to resolve on the link above didn't actually worked on me. Thank you for the help and sorry it's my first time using Stack OverFlow and i already knew that was a big thing to expose the question in a proper way, i did my best ;) – Lourenço Melo May 08 '21 at 14:05

0 Answers0