在单词之间使用空格时输入不匹配异常
Posted
技术标签:
【中文标题】在单词之间使用空格时输入不匹配异常【英文标题】:input mismatch exception while using space in between words 【发布时间】:2021-09-12 13:35:01 【问题描述】:我正在做一个项目,我已经完成了,我有一个非常简单的问题,这让我很困惑。我试图让用户从菜单中输入一个数字,并根据发生的不同情况而定,但是每当我在单词之间输入空格时,我都会收到输入不匹配异常。我在代码的最后一行收到了这个错误,请检查我的代码,谢谢。
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();
【问题讨论】:
显示输入和错误 【参考方案1】:问题在于您对Scanner#next()
的使用,以及想要输入多个以空格分隔的“单词”,例如。 (免责声明:我理解您的问题,因为您想为“名称”输入输入多个单词,此答案以此为先决条件)
请参阅Scanner#next()
Javadoc 的以下摘录:
从此扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是匹配分隔符模式的输入。
Scanner
的默认分隔符是空格。因此,当您向用户请求姓名,而用户想要输入“John Doe”时,只会读取“John”,而会留下“Doe”,这很可能导致您看到的错误。
我建议的解决方法是使用nextLine()
读取整行,同时逐行提供每个输入。
但是,请注意这个问题:Scanner is skipping nextLine() after using next() or nextFoo()?
记住这一点,我将修改您的代码如下:
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();
旁注:
我移动了您的name
和 anotherName
变量的声明,因为它们不必每次都重新声明。
但是,您实际上应该对它们做一些事情(例如,将它们保存在一个列表中,或者用它们创建一些对象),否则它们将在下一次循环迭代中丢失。
您可以省略对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
【讨论】:
以上是关于在单词之间使用空格时输入不匹配异常的主要内容,如果未能解决你的问题,请参考以下文章
C语言:输入一行字符,统计其中有多少个单词,单词之间用空格分隔开
编写程序,输入字符串(包含空格),统计其中单词的个数,单词之间以一个或多个空格分隔。