停止 while 循环

huangapple go评论59阅读模式
英文:

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&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();
	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;

huangapple
  • 本文由 发表于 2020年10月4日 19:47:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64194214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定