java - 为什么scanner.nextInt() != 0 不起作用?
问题描述
我试图弄清楚为什么这不能正常工作,我很困惑。
Scanner scanner = new Scanner(System.in);
while(!scanner.hasNextInt() || scanner.nextInt() != 0) {
System.out.println("Wrong!");
scanner.next();
}
return scanner.nextInt();
如果我输入除 0 以外的任何内容,则上面的代码正确打印输出错误,但在输入 0 时它不会立即终止。相反,我输入 0 一次,然后任何与我之后输入的内容类似的内容都会卡住。
Input: 1, Output: Wrong!
Enter: 0, Output: Nothing
直到我再输入 0 两次后,程序才会终止。
我确实有一个问题,为什么这有效
while(!scanner.hasNextInt() && list.size() > scanner.nextInt()) {
validation(); //Call invalid message function
scanner.nextInt(); //Record user input, integer
}
return scanner.nextInt() - 1; //Return user input
解决方案
Scanner scanner = new Scanner(System.in);
while(!scanner.hasNextInt()/*here*/ || scanner.nextInt() != 0) {
System.out.println("Wrong!");
scanner.next(); // this is also wrong
}
return scanner.nextInt();//this is what is wrong
scanner.next()
正在发生的事情是nextInt()
等待扫描器返回一个值,所以所有这些额外的东西都会导致扫描器等待你满足它的请求。您在 while 循环之后向扫描仪询问另一个整数,解决方案是:
Scanner scanner = new Scanner(System.in);
int i = 0;
while((i = scanner.nextInt()) != 0) {
System.out.println("Wrong!");
}
return i;
也仅在需要时返回一个数字,此方法非常适用于根本不需要返回任何内容的“void”函数。
推荐阅读
- c# - Autofac:有没有办法从容器中获取现有的 LifetimeScope,这样我就可以避免传递它的引用?
- javascript - Chrome扩展Javascript:如何在另一个javascript执行后获取window.location并获取href链接而不重定向
- ionic-framework - 离子 4 未优化 APK
- jmeter - 如何让 JMeter 报告每个 http/jdbc 请求/样本所花费的时间
- kubectl - 无法通过 kubectl 公开特定的 Nodeport
- r - 如何提取两个字符串之间的数字?
- apache-spark - 如何使用 PySpark 1.6 读取镶木地板文件?
- jsf-2 - 如何在 JSF 应用程序中不再需要检测当前的 Backing Bean
- ios - 如何确保只有一个线程正在执行后台上下文块
- python - 我可以使用 child_process 在服务器上生成多个 python 输出吗?