程序应该打印“数字 11 出现不止一次” 然后将 duplicateFound 设置为 true 并退出 while 循环,因为它是 true。 但它也会打印“数字 13 出现不止一次”。
为什么会发生这种情况?如何打破 while 循环,以便在找到第一个重复项 (11) 后它不会继续运行? 这是一个效率问题,因为我只想知道是否存在重复项。 我不在乎有多少。
public class DuplicateNumbers
{
public static void main(String[] name)
{
int[] myArray = { 64, 17, 9, 55, 2, 11, 11, 1, 8, 23, 13, 13};
boolean duplicateFound = false;
while (duplicateFound == false)
{
for(int i = 0; i < myArray.length; i++)
{
for(int j = i + 1; j < myArray.length; j++)
{
if(myArray[j] == myArray[i])
{
System.out.println("The number " + myArray[i] + " occurs more than once.");
duplicateFound = true;
}
}
}
}
if(duplicateFound == false)
{
System.out.println("There are no duplicates.");
}
System.out.println("Array length is " + myArray.length);
}
}
最佳答案
这里有一个更清晰的写法。请注意,它删除了您可能认为需要 while
循环的内容。它在 for
循环中使用 return
语句而不是 break
,在我看来这是一种更简洁的处理循环结果的方法。
public class DuplicateNumbers
{
private static boolean hasDuplicates(int[] myArray) {
for(int i = 0; i < myArray.length; i++)
{
for(int j = i + 1; j < myArray.length; j++)
{
if(myArray[j] == myArray[i])
{
System.out.println("The number " + myArray[i] + " occurs more than once.");
return true;
}
}
}
return false;
}
public static void main(String[] name)
{
int[] myArray = { 64, 17, 9, 55, 2, 11, 11, 1, 8, 23, 13, 13};
if (!hasDuplicates(myArray)) {
System.out.println("There are no duplicates.");
}
System.out.println("Array length is " + myArray.length);
}
}
关于java - 当不满足条件时,while 循环不会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22255401/