在单词之间使用空格时出现输入不匹配异常



我正在做一个项目,我已经完成了,我有一个非常简单的问题,这让我非常困惑。我试图让用户从菜单中输入一个数字,根据不同的情况,但每当我在单词之间键入空格时,就会出现输入不匹配的异常。我在代码的最后一行遇到了错误,请检查下面的代码,谢谢。

System.out.println("Enter: " + "n1.Enter Name" +"n2.Enter another name" + "n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "n1.Enter Nmame" +"n2.Enter another name" + "n3.Exit");
userChoice = kb.nextInt();
}

问题在于您对Scanner#next()的使用,以及想要输入多个"单词";例如用空格分隔。(免责声明:我理解你的问题,因为你想在"名称"输入中输入多个单词,这个答案将其作为先决条件(

请参阅Scanner#next()Javadoc的以下摘录:

从该扫描程序中查找并返回下一个完整的令牌。完整的标记前面和后面都是与分隔符模式匹配的输入。

Scanner的默认分隔符是空白。因此,当您向用户请求一个名称,并且用户想要输入"时;John Doe";,仅";约翰;将被读取,并且";Doe";将被留下,很可能导致您看到的错误。

我建议的解决方法是使用nextLine()读取整行,同时逐行提供每个输入。

但是,请注意这个问题:扫描仪在使用next((或nextFo((后是否跳过nextLine((?

记住这一点,我会修改你的代码如下:

String name = "";
String anotherName = "";
System.out.println("Enter: " + "n1.Enter Nmame" +"n2.Enter another name" + "n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "n1.Enter Nmame" +"n2.Enter another name" + "n3.Exit");
userChoice = kb.nextInt();     
}

旁注:

  • 我移动了nameanotherName变量的声明,因为它们不必每次都重新声明
  • 然而,您实际上应该对它们做些什么(例如,将它们保存在列表中,或用它们创建一些对象(,否则它们将在下一次循环迭代中丢失
  • 您可以省略对if (userChoice == 3)的检查,因为这永远不会与while (userChoice != 3)结合使用

示例输入:

Enter: 
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3

最新更新