16
import java.util.Scanner;
class MyClass
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        int employeeId, supervisorId;
        String name;
        System.out.println("Enter employee ID:");
        employeeId = scanner.nextInt();
        System.out.println("Enter employee name:");
        name = scanner.next();
        System.out.println("Enter supervisor ID:");
        supervisorId = scanner.nextInt();
    }
}

我在尝试输入名字和姓氏时遇到了这个异常。

Enter employee ID:
101
Enter employee name:
firstname lastname
Enter supervisor ID:
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at com.controller.Menu.<init>(Menu.java:61)
    at com.tests.Employeetest.main(Employeetest.java:17)

但如果我只输入名字,它就可以工作。

Enter employee ID:
105
Enter employee name:
name
Enter supervisor ID:
501

我想要的是读取完整的字符串,无论它是以 asname还是 as给出的firstname lastname。这里有什么问题?

4

4 回答 4

26
Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

呼叫nextInt()是一个问题,因为它没有拿起新线路(当您按 Enter 时)。所以,在那之后打电话scanner.nextLine()就可以了。

于 2013-07-17T04:41:49.183 回答
1

您可以做的是使用分隔符作为新行。直到您按下回车键,您才能将其读取为字符串。

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

希望这可以帮助。

于 2013-07-17T04:40:08.677 回答
1

代替:

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

和:

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

这是因为 next() 只抓取下一个标记,并且空格充当标记之间的分隔符。我的意思是,扫描仪将输入:“firstname lastname”作为两个单独的标记读取。因此,在您的示例中, ename 将设置为 firstname 并且扫描仪正在尝试将 supervisorId 设置为 lastname

于 2013-07-17T04:45:57.550 回答
0

您正在向 nextInt 输入空值,如果您提供空值,它将失败...

我在这段代码中添加了一个空检查

试试这个代码:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}
于 2013-07-17T04:44:13.533 回答