How to read strings from a Scanner in a Java console application?

后端 未结 4 594
萌比男神i
萌比男神i 2020-12-01 18:46
import java.util.Scanner;
class MyClass
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        int employeeId,          


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 19:05

    Replace:

    System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
    

    with:

    System.out.println("Enter EmployeeName:");
                     ename=(scanner.nextLine());
    

    This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

提交回复
热议问题