user805981
user805981

Reputation: 11059

How do I check for a boolean for existence of a number between a range of two numbers in java?

I cannot figure out how to prove an existence is true or not;

static boolean existsx(double p1x, double p2x,double[] varray) {
    boolean foundx = false;
    int i;
    //System.out.println(varray.length);

    for (double v : varray){
      if ( varray[i] > p1x &&  v < p2x) {
            foundx = true;
            //System.out.println(x+" was found to be between"+p1x+" and "+p2x);
            break;
       }
       else {
          foundx = false;
       }
    }
    return foundx;
} 

I'm trying to check for an existence of a number in an array between p1x and p2x. If it is true then, return true, else return false.

Upvotes: 0

Views: 200

Answers (4)

Walter Laan
Walter Laan

Reputation: 2976

You could also use a SortedSet (if you need to do the look up often and the varray is large it should be faster is you create it once):

import java.util.SortedSet;
import java.util.TreeSet;

public class TestSortedSet {
    public static void main(String[] args) {
        double p1 = 2;
        double p2 = 4;
        double[] varray = { 3.0 };
        TreeSet<Double> set = new TreeSet<Double>();
        for(double d : varray) {
            set.add(d);
        }

        SortedSet<Double> between = set.subSet(p1, p2);
        System.out.printf("%s number(s) between %s and %s: %s", between.size(), p1, p2, between);
    }
}

Upvotes: 0

npinti
npinti

Reputation: 52185

I think you have a few logical issues, declaring the variable i without ever initializing it being one of them.

The following code should tell you if one of the numbers in the given array is in between those two:

static boolean existsx(double p1x, double p2x,double[] varray){
    double upperBound = Math.max(p1x, p2x);
    double lowerBound = Math.min(p1x, p2x);

    for (double number : varray)
    {
       if ( (number <= upperBound) && (number >= lowerBound))
       {
           return true;
       }
    }

    return false;
} 

Upvotes: 3

Eng.Fouad
Eng.Fouad

Reputation: 117597

public static boolean exists(double p1, double p2, double[] varray)
{
    for(double v : varray)
        if(v >= p1 && v <= p2) return true;
    return false;
} 

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501043

You're trying to use a mixture of the enhanced for loop and a "normal" for loop. Also, you're going through hoops to avoid multiple exits. I'd rewrite it as:

static boolean existsx(double p1x, double p2x, double[] varray) {
    for (double v : varray){
        if (v > p1x && v < p2x) {
            return true;
        }
    }
    return false;
}

(Note that that's currently *excluding p1x and p2x; you may want to make at least one bound inclusive, depending on your needs. Renaming the parameters and method wouldn't hurt, either.)

Upvotes: 5

Related Questions