代码不起作用
这段代码应该打印“inside if”一词,但没有打印,我不知道它出了什么问题。
doublesArray[0] = 3;
doublesArray[1] = 3;
doublesArray[2] = 3;
doublesArray[3] = 0;
int[] temp6 = {3,3,3,0};
//length is 4 for both arrays
if(doublesArray.equals(temp6))
System.out.println("Inside if");
这些内容表明它应该打印正确
int[] temp6 = {3,3,3,0};
doublesArray[0] = 3;
doublesArray[1] = 3;
doublesArray[2] = 3;
doublesArray[3] = 0;
//length is 4 for both arrays
System.out.println("temp6 " + temp6[0] + " " + temp6[1] + " " + temp6[2] + " " + temp6[3]);
System.out.println("doublesArray " + doublesArray[0] + " " + doublesArray[1] + " " +
doublesArray[2] + " " + doublesArray[3]);
System.out.println("This should be true: ");
System.out.println("doublesArray.equals(temp6) = " + doublesArray.equals(temp6) + "\n");
//testing
if(doublesArray[0] == temp6[0])
System.out.println("correct");
if(doublesArray[1] == temp6[1])
System.out.println("correct");
if(doublesArray[2] == temp6[2])
System.out.println("correct");
if(doublesArray[3] == temp6[3])
System.out.println("correct");
//testing with numbers
System.out.println(" ");
if(doublesArray[0] == 3)
System.out.println("CORRECT");
if(doublesArray[1] == 3)
System.out.println("CORRECT");
if(doublesArray[2] == 3)
System.out.println("CORRECT");
if(doublesArray[3] == 0)
System.out.println("CORRECT");
这些是我得到的结果,应该表明 doublesArray.equals(temp6) = true
temp6 3 3 3 0
doublesArray 3 3 3 0
This should be true:
doublesArray.equals(temp6) = false
correct
correct
correct
correct
CORRECT
CORRECT
CORRECT
CORRECT
感谢那些能够提供帮助的人。
最佳答案
doublesArray.equals(temp6) 与 array1 == array2 相同, 即它是同一个数组吗?
Arrays.equals(array1, array2) 比较数组的内容。
public static void main(String[] args) {
int[] doublesArray = new int[4];
doublesArray[0] = 3;
doublesArray[1] = 3;
doublesArray[2] = 3;
doublesArray[3] = 0;
int[] temp6 = { 3, 3, 3, 0 };
// length is 4 for both arrays
if (Arrays.equals(temp6, doublesArray)) {
System.out.println("Inside if");
}
}
输出
Inside if
关于java - Array.equals(...) 给出了不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27682956/