等于运算符在 if 语句中不起作用

Equals Operator not working within if statement

由于某些原因,我的程序不允许if语句if (arr == arr[i]),表示==运算符不能应用于double[],double。但是,它适用于我的朋友程序。为什么它不起作用,我该如何解决?这是我的代码:

import java.util.Arrays;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("What length (in a whole number) would you like the array to be? ");
        int arraySize = sc.nextInt();

        double[] arr = new double[arraySize];
        for (int i = 0; i < arraySize; i++) {
            int requiredInput = arraySize - i;
            System.out.println("Please enter " + requiredInput + " more 'double' numbers.");
            arr[i] = sc.nextDouble();
        }

        System.out.println("What 'double' would you like to find the first and last indexes of?");
        double searchIndex = sc.nextDouble();

        for (int i = 0; i <= arraySize; i++) {
            if (arr == arr[i]) {

            }
        }

            System.out.println(Arrays.toString(arr));

      
    }
}

如果 searchIndex 是要搜索的双精度值,那么您的 if() 应该如下所示。

if (arr[i] == searchIndex) {
     indexPresent = true;
     break;
}

看来这就是您要执行的操作。从控制台获取一个双精度值并在双精度数组中找到该双精度的索引。为此,您需要保存索引。

int index = -1;
System.out.println("What 'double' would you like to find the first and last indexes of?");
double doubleToFind = sc.nextDouble();
for (int i = 0; i < arr.length; i++) {
    if (doubleToFind == arr[i]) {
         index = i;  // save the index (location in the array)
         break;
    }
}

循环完成后,您可以执行类似的操作。

if (index == -1) {
    System.out.println("Value not found");
} else {
    System.out.println(doubleToFind + " is at index " + index);
}