Java程序查找数组中的所有值是否相等

时间:2016-02-17 21:06:09

标签: java arrays loops for-loop equals

该程序将打印一份声明,说明它们何时相等,但不是在它们不相同时。有什么问题?

int k = 0;
while (k < numbers.length - 1 )
{
    if(numbers[k]==numbers[k+1])
    {
        k++;
    }

}
if(k == numbers.length - 1)
{
    System.out.println("All the numbers are the same");  
}
else 
{
    System.out.println("All the numbers are not the same");  
} 

3 个答案:

答案 0 :(得分:2)

你有一个无限循环,见:

int[] numbers = {3,3,5,3,3};
int k = 0;
while (k < numbers.length - 1 ) // k never be k >= numbers.length - 1
{ 
    if(numbers[k]==numbers[k+1]) // if not, k never increase
    {
        k++;
    }

}
if(k == numbers.length - 1)
{
    System.out.println("All the numbers are the same");
}
else
{
    System.out.println("All the numbers are not the same");
}

您可以使用以下代码代替解决方案:

private static boolean isEqual(int[] numbers) {
    Integer oldNumber = null;
    for(int number: numbers) {
        if(oldNumber != null && oldNumber != number) {
            return false;
        }
        oldNumber = number;
    }
    return true;
}

public static void main(String[] args) {
    int[] numbers = {3,3,5,3, 3};


    if(isEqual(numbers))
    {
        System.out.println("All the numbers are the same");
    }
    else
    {
        System.out.println("All the numbers are not the same");
    }
}

答案 1 :(得分:1)

更改您的代码以使用for循环,并在找到差异时突破:

boolean allSame = true;
for(int i = 0; i < numbers.length - 1; i++)
{
    if(numbers[i]!=numbers[i+1])
    {
        allSame = false;
        break;
    }
}

if(allSame)
{
    System.out.println("All the numbers are the same");  
}
else 
{
    System.out.println("All the numbers are not the same");  
}

答案 2 :(得分:-1)

试试这个:

boolean allSame = true;
while (allSame == true) {
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[0] != numbers[i+1]) {
            allSame = false;
        }
    }
}

//Lets user know if array contained same elements or not
if (allSame) {
    System.out.println("All the numbers are the same. ");  
}
else {
    System.out.println("Not all numbers are the same. ");  
}

查看for循环中的“numbers [0]”。我们总是可以将所有元素与第一个元素进行比较,因为如果它们一次不相同,显然它们并不完全相同。