我听说使用 while(true) 是一种不好的编程习惯。
因此,我编写了以下代码来从用户那里获取一些数字(使用默认值)。但是,如果用户碰巧输入了-1,那么它将为他们退出程序。
那么这应该怎么写呢(真的)?我可以想出一个条件来使 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);
}
}