我是java的新手,我正在试图弄清楚我的编码出了什么问题。每次我输入一封信都会崩溃?如下图所示。
读入标记
ý
错误plz输入数字
输入下一个学生标记
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 histogram.Histogram.main(Histogram.java:95)
bC:\Users\Chevon\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
这是我的代码:
int cat1 = 0;// Category 1
int cat2 = 0;// Category 2
int cat3 = 0;//Category 3
int cat4 = 0;//Category 4
int mark = 0;// Total marks that the user enters
int counter = 0;
double Average = 0;
int Total_mark = 0;
int pass=0;
int highest = 0;
int lowest = 101;
Scanner input = new Scanner(System.in);
System.out.println("Read in a mark");
try{
mark= input.nextInt();
System.out.println("The number you enter is "+mark);
}catch(InputMismatchException e){
System.out.println("Error plz enter a number");
}
while(mark<0){
System.out.println("Enter a positive integer");
mark = input.nextInt();
}
我预计它会像这样
读入标记
ý
错误plz输入数字
输入下一个学生标记
4
答案 0 :(得分:0)
在您的代码中,catch
仅适用于第一个用户输入。
您应该添加另一个catch
来处理下一个用户输入中的InputMismatchException
。否则,异常会上升,如果输入不是数字,则保留方法。
试试:
try{
mark= input.nextInt();
System.out.println("The number you enter is "+mark);
}
catch(InputMismatchException e){
System.out.println("Error plz enter a number");
}
while(mark<0){
try{
System.out.println("Enter a positive integer");
mark = input.nextInt();
}
catch(InputMismatchException e){
System.out.println("Error plz enter a number");
}
}