为什么在此基本Java程序中获得InputMismatchException? [英] Why get an InputMismatchException in this elementary Java program?
本文介绍了为什么在此基本Java程序中获得InputMismatchException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String[] names=new String[4];
int[] scores=new int[4];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 4 strings and integers:");
for(int i=0;i<4;i++){
names[i]=keyboard.nextLine();
scores[i]= keyboard.nextInt();
}
上面是我的简单程序,下面显示了弹出的异常。 / p>
Above is my simple program and the following shows the exception that pops up.
Enter 4 strings and integers:
first
1
second
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Q2.main(Q2.java:15)
Java Result: 1
推荐答案
nextInt
不会占用行尾,而是保留在缓冲区中。因此,当您按下 1 enter 时, 1
会被读入第一个分数
,然后将第二个名称
设置为空字符串。
nextInt
doesn't swallow the end of line, that stays in the buffer. So when you hit 1enter, 1
is read into the first score
, then the second name
is set to an empty string.
然后解析器尝试解释秒
作为 int
,引发异常。
Then the parser tries to interpret second
as an int
, raising the exception.
您需要在 readInt
之后丢弃当前行。
You'll need to discard the current line after the readInt
.
这篇关于为什么在此基本Java程序中获得InputMismatchException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文