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
我想要的是阅读完整字符串,无论是name
还是firstname lastname
。这有什么问题?
答案 0 :(得分:23)
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()
是一个问题,因为它没有拿到新行(当你点击输入时)。因此,在此之后调用scanner.nextLine()
可以完成工作。
答案 1 :(得分:1)
您可以使用分隔符作为新行。直到你按回车键,你就可以把它读成字符串。
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
希望这会有所帮助。
答案 2 :(得分:1)
替换:
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
使用:
System.out.println("Enter EmployeeName:");
ename=(scanner.nextLine());
这是因为next()只抓取下一个标记,空格充当标记之间的分隔符。通过这个,我的意思是扫描程序读取输入:“firstname lastname”作为两个单独的标记。因此,在您的示例中,ename将设置为firstname,扫描程序正在尝试将supervisorId设置为lastname
答案 3 :(得分: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
}
}