我的应用程序有一个循环,重复相同的选择,直到被告知退出。
Scanner scan = new Scanner(System.in);
while(running == true){
System.out.println("Select an option (1-4):");
System.out.println("1: Add an item to your store");
System.out.println("2: Search for an item in your store");
System.out.println("3: Remove an item from your store");
System.out.println("4: Buy an item from the store:");
System.out.println("5: Exit this application");
int option = scan.nextInt();
if(option == ... etc.
}
在循环的第二次迭代中,插入的整数不会被接受并返回以下错误:
线程“main”中的异常java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864)at java.util.Scanner.next(Scanner.java:1485)at java.util.Scanner.nextInt(Scanner.java:2117)at java.util.Scanner.nextInt(Scanner.java:2076)at storeproject.StoreProject.main(StoreProject.java:27)
答案 0 :(得分:0)
你得到这个InputMismatchException
,因为你的输入不是数字,可能是非数字数据,也可能不是整数,因为你试图得到nextInt()
。希望它能帮到你!
答案 1 :(得分:0)
我想我知道发生了什么。
下一个int需要有一个数字而且只有一个数字。输入之前或之后的任何非整数值,alpha和标点符号都会给出错误。我试了一下:
<强>代码:强>
public class ScannerTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("Select an option (1-4):");
System.out.println("1: Add an item to your store");
System.out.println("2: Search for an item in your store");
System.out.println("3: Remove an item from your store");
System.out.println("4: Buy an item from the store:");
System.out.println("5: Exit this application");
int option = scan.nextInt();
System.out.println(option);
}
}
}
<强>输出:强>
5
5
Select an option (1-4):
1: Add an item to your store
2: Search for an item in your store
3: Remove an item from your store
4: Buy an item from the store:
5: Exit this application
6
6
Select an option (1-4):
1: Add an item to your store
2: Search for an item in your store
3: Remove an item from your store
4: Buy an item from the store:
5: Exit this application
5.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at ScannerTest.main(ScannerTest.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
答案 2 :(得分:-1)
尝试
while (scan.hasNextInt() && running)