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

Java程序-查找数组中的所有值是否相等,java,arrays,loops,for-loop,equals,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 { Sy

当它们都相等时,此程序将打印一条语句,但当它们不相等时则不会打印。怎么了

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");  
} 
intk=0;
而(k
如果有一个无限循环,请参见:

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");
}

将代码更改为使用
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");  
}
boolean allSame=true;
对于(int i=0;i
试试这个:

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. ");  
}
boolean allSame=true;
while(allSame==true){
for(int i=0;i

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

numbers[k]
不等于
numbers[k+1]
时会发生什么?或者,更具体地说,什么没有发生?那么,预期会发生什么呢?在
while
循环的每个迭代中打印值ok
k
。您可能会在那里发现一些东西。它会导致无限循环,因为如果值不同,您不会增加
k
变量。无限循环通常来自
while
语句。尽量避免
语句。实际上,你可以用
for
语句替换它们,因为它们不太容易出错。实际上,OP也可以将所有数字放入
集合
中,并检查其大小是否为1…同意-这个问题有很多解决方案-我只是试图保持它与原始代码相对类似。可能是,你的意思是
boolean allSame=true而不是
int allSame=true?是的-我的大脑在想,但我的手指没有打出来。:)否。它之所以有效,是因为等式检查中的
数字[i+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. ");  
}