如何从Java循环中删除while(true)? [英] How can I remove the while(true) from my loop in Java?

查看:177
本文介绍了如何从Java循环中删除while(true)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说使用while(true)是一种不好的编程习惯.

I've heard that using while(true) is a bad programming practice.

因此,我编写了以下代码来从用户那里获取一些数字(具有默认值).但是,如果用户碰巧输入-1,它将为他们退出程序.

So, I've written the following code to get some numbers from a user (with default values). However, if the user happens to type in -1, then it will quit the program for them.

如果没有一会儿(真),应该怎么写呢?我可以想到一个条件,可以使while循环关闭,而不会立即继续进行直到下一次迭代?

How should this be written then without a while(true)? I can think of a condition to make the while loop go off that will get caught right away without continuing on until the next iteration?

这就是我现在的样子:

 public static void main(String[] args)
    {
        System.out.println("QuickSelect!");

        while (true)
        {
            System.out.println("Enter \"-1\" to quit.");

            int arraySize = 10;
            System.out.print("Enter the size of the array (10): ");
            String line = input.nextLine();
            if (line.matches("\\d+"))
            {
                arraySize = Integer.valueOf(line);
            }

            if (arraySize == -1) break;

            int k = 1;
            System.out.print("Enter the kth smallest element you desire (1): ");
            line = input.nextLine();
            if (line.matches("\\d+"))
            {
                k = Integer.valueOf(k);
            }

            if (k == -1) break;

            List<Integer> randomData = generateRandomData(arraySize, 1, 100);

            quickSelect(randomData, k);
        }
    }

推荐答案

while (true)很好.保留它.

如果您有一个更自然的终止条件,我会说要使用它,但是在这种情况下,正如其他答案所证明的,摆脱while (true)会使代码更难理解.

If you had a more natural termination condition, I'd say to use it, but in this case, as the other answers prove, getting rid of while (true) makes the code harder to understand.

这篇关于如何从Java循环中删除while(true)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆