英文:
Stopping while loop
问题
能有人帮我停止这个无限循环吗?
**只有当输入是字符串时,这个循环应该停止。**
所有的数字应该被添加到一个列表中。
谢谢!
public static void main(String[] args) {
addDigitsToList();
}
public static void addDigitsToList() {
ArrayList<Integer> list = new ArrayList<Integer>();
int input = 0;
while (true) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
input = Integer.parseInt(reader.readLine());
list.add(input);
} catch (NumberFormatException | IOException e) {
for (Integer integer : list) {
System.out.println(integer);
}
}
}
}
英文:
can anybody help me to stopp this infity loop?
This loop shoud stopp if an input is a String.
All digits should be added to a list.
Thank you!
public static void main(String[] args) {
addDigitsToList();
}
public static void addDigitsToList() {
ArrayList<Integer> list = new ArrayList<Integer>();
int input = 0;
while (true) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
input = Integer.parseInt(reader.readLine());
list.add(input);
} catch (NumberFormatException | IOException e) {
for (Integer integer : list) {
System.out.println(integer);
}
}
}
}
答案1
得分: 1
如果你想要停止无限循环,可以使用关键词
break;
在你希望停止的条件上。你告诉我们当输入是字符串时要停止,那么你应该更新你的代码-
英文:
If you want to stop the infinity loop than use the keyword
break;
on which condition you want to stop it. You told us to stop when the input is a string than you should update your code-
答案2
得分: 0
在 for 循环之后添加以下代码:
break;
英文:
Right after the for loop add this :
break;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论