java - 如果用户输入特定关键字,如何停止从扫描仪读取?
问题描述
我需要能够在控制台中输入随机数的整数,然后在完成后输入一个特殊字符,例如 Q。但是,我不确定如何验证输入是否为 int。
关键是用户输入 x 数量的整数,这些整数从客户端发送到服务器,服务器从一个简单的方程返回结果。我计划一次发送一个,因为它可以输入任意数量的整数。
我尝试了几种不同的方法。我尝试过使用 hasNextInt。我尝试了 nextLine 然后将每个输入添加到 ArrayList 然后解析输入。
List<String> list = new ArrayList<>();
String line;
while (!(line = scanner.nextLine()).equals("Q")) {
list.add(line);
}
list.forEach(s -> os.write(parseInt(s)));
这是我最初验证输入的另一个循环,但我不确定完成后如何退出循环。
while (x < 4) {
System.out.print("Enter a value: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input: Integer Required (Try again):");
}
os.write(scanner.nextInt());
x++;
}
任何帮助,将不胜感激。谢谢
解决方案
干得好:
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.equals("Q")) {
scanner.close();
break;
}
try {
int val = Integer.parseInt(line);
list.add(val);
} catch (NumberFormatException e) {
System.err.println("Please enter a number or Q to exit.");
}
}
推荐阅读
- java - 尝试创建新文件会引发 FileNotFoundException 但文件存在于同一包中
- html - 内容 CSS 和与 IE 的兼容性
- c# - 对 Task 对象的引用未指向新的 Task
- python - AttributeError: exp 在使用 scipy.io.loadmat 加载的数据上使用 numpy
- c# - 如何使用自动类型转换展开对象数组以进行函数调用?
- sql - SQL 将员工姓名和薪水列在另一个之下
- ios - Xcode 10 多个命令为 Pods 依赖构建错误
- postgresql - 刷新物化视图 CONCURRENTLY 导致表膨胀
- php - 单击下拉条目后过滤 html 表格结果
- node.js - Mocha-webpack 未找到“fs”模块