java - 使用 printf() 和 nextInt() 方法显示时,Scanner hasNext() 无限循环
问题描述
我有这段代码在 do-while 循环中询问姓名和年龄:
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d",
scanner.next(), scanner.nextInt());
} while (scanner.hasNext());
}
}
它输出:
Enter name & age: test 6
test 6
然后似乎对我的输入没有反应,虽然它应该在第三行重复了这个问题。这里有什么问题?
解决方案
java.util.Scanner.hasNext() 方法 如果此扫描器的输入中有另一个标记,则返回 true。此方法可能会在等待输入扫描时阻塞。扫描仪不会超过任何输入。阅读更多
为了避免被 hasNext() 阻塞,你可以简单地传递 true for 循环条件。
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Enter name & age: ");
System.out.printf("%s %d", scanner.next(), scanner.nextInt());
} while (true);
}
}
推荐阅读
- c# - 在 C# Winforms 应用程序中键入时如何搜索 SQL Server 数据库?
- amazon-web-services - 为导入的 Kinesis 流获取 ARN
- go - 错误; 不能在 appendgo 中使用 imageName(类型 ImageName)作为类型 dao.ImageName
- python - 函数的副作用
- ruby-on-rails - 带有魔法宝石的多个模型
- angular - 在 dist 文件夹中构建 ng 后应该有多少个文件
- c# - 在 WPF 应用程序中的画布上仅呈现特定的几何图形数据
- webview - 是否可以在浏览器堆栈设备中使用 appium 运行 webview 自动化脚本
- java - 有没有办法在 morphia 中编写否定查询( ex nand , nor , not )
- elasticsearch - 如何使用 Painless 拒绝弹性搜索索引结果中的 json 数据类型列中的值?