我听说使用while(true)是一种不好的编程实践。
因此,我编写了以下代码来获取用户输入的一些数字(带有默认值)。 但是,如果用户输入-1,则会为他们退出程序。
那么,没有while(true)应该如何编写呢? 我可以考虑一个条件,使while循环立即结束,而不会继续进行下一次迭代吗?
以下是我目前的代码:
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);
}
}
for(;;)
而不是while(true)
- 我似乎找不到参考资料,但所有Sun的代码和教程都使用for(;;)
而不是while(true)
。 - Pete Kirkhamwhile(true)
更清晰,因此更好。 - Stephen Cwhile(true)
。理由: https://dev59.com/dnM_5IYBdhLWcg3wWRkF - Dave Jarvis