java - 输入某行后如何停止扫描?
问题描述
我想构建一个只停止扫描字符串的程序,直到我在控制台中输入“0”之后,我该怎么做?
我假设我可以使用 do while 循环,但我不知道在 while() 条件中放入什么。
Scanner scan = new Scanner(System.in);
do {
String line = scan.nextLine();
//do stuff
} while(); //what do i put in here to stop scanning after i input "0"
在此先感谢,总的来说,我是 Java 和 OOP 的新手。
解决方案
您可以使用 while 循环代替 do-while 循环。定义一个将在 while 循环内初始化的字符串。在每次迭代中,我们将 String 分配给 Scanner#nextLine 并检查该行是否不等于 0。如果是,则 while 循环会阻止迭代。
Scanner scan = new Scanner(System.in);
String line;
while (!(line = scan.nextLine()).equals("0")) {
System.out.println("line: " + line);
}
推荐阅读
- java - 我正在使用斐波那契数,其中第 n 个数的“n”为 5-6 位。我怎样才能减少执行所需的时间?
- php - 查找html标签的正则表达式
- symfony - EasyaAmin 3 - 根据底层实体动态隐藏/显示操作
- python - 如何在 Python 中基于 2D 数组对 NumPy 3D 数组进行索引?
- firebase - 全局对象和本地对象 [firebase] 之间的区别
- python - Selenium Python AttributeError:“NoneType”对象没有属性“send_keys”
- javascript - 日期选择器跳过禁用的一天 Javascript
- node.js - Node.js(快速框架):发布方法不起作用
- graphql - 为什么这个 graphql 显示 TypeError: (...) is undefined
- php - 为什么 laravel 默认注销下拉菜单不起作用?