java - java - 如何通过让用户在java中按下键盘上的特定键来终止无限控制台循环?
问题描述
大家好,你们可以看到这是一个无限循环,我问我是否可以在键盘上分配一个键,只要用户按下这个键,它就会终止并停止这个循环。请注意,我正在尝试在控制台中执行此操作,而不是 UI
do{
//some calculations here
}while(true);
```
解决方案
做你想做的两个例子:
第一个例子:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
} while(!input.equalsIgnoreCase("x"));
sc.close();
第二个例子:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
if (input.equalsIgnoreCase("x")) {
break;
}
} while(true);
sc.close();
推荐阅读
- java - Java同时处理多个请求
- docker - 为什么删除未请求的包(docker build)?
- intellij-idea - Intellij 创建测试缺少 JUnit
- c# - asp net core: [FromRoute] 和模型绑定
- python - 使用 Fabric 运行本地命令
- c# - Mongodb 集合为动态
- javascript - 在 NPM 安装上触发准备
- sql - 无法将 plpgsql 中的自定义类型对象设置为 null。相反,该对象的字段变为空
- javascript - 在 Babel 旁边使用 eslint-plugin-compat
- javascript - 需要跟踪 setTimeout 调用以防我以后需要取消它们?