Search code examples
javaarraysequals

Equals Operator not working within if statement


For some reason, my program won't allow the if statement if (arr == arr[i]), saying that the == operator cannot be applied to double[], double. However, it works on my friends program. Why doesn't it work, and how I can fix it? Here is my code:

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

      
    }
}

Solution

  • It appears this is what you are trying to do. Take a double value from the console and find the index of that double in an array of doubles. To do this, you need to save the index.

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

    Once the loop is done, you can do something like this.

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