user102817
user102817

Reputation: 307

How to find if a number is in an array?

Trying to write a method to tell me if a number is in an array or not. So far I have..

    public static boolean inList(double number, double[] list){
    for (double i : list)
        {
            if (i == number){
                return false;
        }

    }
    return true; //if its not in the array I want the if statement to run.
}

So far this hasn't worked for me, for some reason it can't identify when some numbers are in the array or not.

Upvotes: 1

Views: 769

Answers (4)

claj
claj

Reputation: 5402

One thing to think of when comparing doubles is that they are not entirely distinct in their representations. This means that 1.0 + 2.0 not nescessarily equals 3.0, but could equal 2.999999.... or 3.000001.

A good thing would be to use a comparision which allowed a little slack (an epsilon) that made it possible to have the value you compare with to some (very close) distance to the numbers you compare with.

So something like:

public static boolean inList(double number, double[] list){
    for (double i : list)
        {
            if (Math.abs(i - number) < 0.0000000001){
                return true;
        }

    }
    return false; //if its not in the array I want the if statement to run.
}

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39457

You need to swap the true and false in your code.

If you have equality there, then it's in the list, otherwise it is not in the list.

Also, generally don't compare doubles a and b with ==. Use

something like: Math.abs(a - b) < EPS, where EPS = 0.00001 let's say.

Upvotes: 2

claj
claj

Reputation: 5402

If you want to do serious stuff with java arrays, don't miss java.util.Arrays!

A function for finding a number in a (sorted) array would be:

double[] theArray = {1.24, 5.23, 1.1, 6.466, 35.1, 34.0};
java.util.Arrays.sort(theArray); //for binarySearch to work

public static boolean inArray(double i, double[] theSortedArray){
     return (java.util.Arrays.binarySearch(i, theSortedArray) >=0);
}

Upvotes: 1

You mixed up your return statements. It should be so:

    public static boolean inList(double number, double[] list){
        for (double i : list)
        {
            if (i == number){
                //return true when you've found the match!
                return true;
            }
        }
    //return false here because you finished looking at the entire array 
    //and couldn't find a match.
    return false;
}

Upvotes: 6

Related Questions