我不是 Java 专家,但我有一个问题。我使用 Scanner 从键盘获取数据,但在将数据注册到数组之前我必须进行 2 次验证。一是数据不必是字符串,我使用 !in.hastNextInt()
来验证 Scanner 实例,另一个是数据不必是字符串为0
。我正在使用的代码是下一个:
Scanner in = new Scanner(System.in);
int chain [] = new int [10];
System.out.println("Welcome, please enter the values for the array: ");
for(int x = 0;x < chain.length; x++) {
System.out.print((x+1) +": ");
while(!in.hasNextInt() || in.nextInt()==0) {
System.out.print("This app doesn't accept letters, symbols or zeros: ");
in.next();
}
chain[x] = in.nextInt();
}
不幸的是,当我运行该程序时,它对每个语句询问我两次,例如,对数组的每个位置 0 询问两次,对数组的每个位置 1 询问两次。
有人知道发生了什么吗?
它与 !in.hasNextInt()
完美配合,但是当我使用 in.nextInt()==0
时,或者当我仅使用 in. nextInt()==0
单独
我的错误是什么,您建议我更改代码以使其正常工作。 我很感激任何帮助
提前谢谢
正如 @Andreas 在他的回答中所说,我必须更改我的代码,新的好的代码是:
for(int x = 0;x < chain; x++) {
System.out.print((x+1) +": ");
while(!in.hasNextInt()) {
System.out.print("This app doesn't accept letters or symbols: ");
in.next();
}
chain[x] = in.nextInt();
if(chain[x] == 0) {
System.out.println("This app doesn't accept 0");
--x;
}
}
最佳答案
nextInt()
消耗 token ,因此当您执行in.nextInt()==0
时,您会读取 token 并循环如果该值为零。
如果 token 不为零,则循环结束并执行chain[x] = in.nextInt()
,它读取下一个 token 。不再是同一个 token 。
您应该捕获变量中的值,然后检查是否为零,并在适当的情况下使用它。
关于Java:nextInt() 验证不起作用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368565/