如何在未定义数组长度的Java中输入?
我的输入是这种格式:
1 2 3 4 5 6
Alice
阵列长度尚不清楚。 我以这种方式进行了编码:
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int i=0;
while(sc.hasNext()){
arr.add(sc.nextInt());
}
String player = sc.nextLine();
}
}
但是我遇到了这个错误。
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您看到
java.util.inputMismatchException
是因为您向语句sc.nextint()
提供了输入“ alice” 't知道如何将java.lang.string
输入转换为int(这是next> nextint()
)。这是一个非常简单的示例,可以重现相同的行为:
如果您运行这两行并输入非授权程序,例如“ d”,它将引发一个例外:
要修复它,您需要替换
nextint()
nextint()< /code>具有耐受性输入的东西,可能
nextline()
。这是一个(非常)简单的示例,显示如何工作。请注意,这只是突出显示您要问的行为,即:如何解决
inputMismatchException
。与您的原始程序一样,没有循环终止 - 它将永远运行(直到您退出程序)。The reason you are seeing
java.util.InputMismatchException
is because you provided input "Alice" to the statementsc.nextInt()
, and the scanner is telling you that it doesn't know how to convert ajava.lang.String
input to an int (which is the return type ofnextInt()
).Here's a very simple example that reproduces the same behavior:
If you run those two lines and enter a non-integer, like "d", it will throw an exception:
To fix it, you need to replace
nextInt()
with something that is tolerant of non-numeric input, possiblynextLine()
. Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you're asking about, namely: how to addressInputMismatchException
. As with your original program, there is no loop termination – it will run forever (until you quit the program).您应该使用
hasnextint
检查整数输入。一旦不再是整数,只需使用next()
读取播放器即可。示例输入的支持
输出
You should use
hasNextInt
to check for integer input. Once no more integers, then just usenext()
to read the player.Example input's supported
output