0

I have the method threshold(double[] a, double x) that takes a list (a) and a numerical value (x) and returns all the values within a that are greater than x. I am having trouble adding the elements greater than x to a new list containing elements of type double. Here is what I have so far:

public static double[] threshold(double[] a, double x)
{
    List<double> ell = new ArrayList<double>();
    p = d >x;
    ell.add(p);
    answer5 = ell;
    return answer5;
}
1
  • 1
    double[] is not the same thing as List<double>. In fact, the latter won't even compile. Commented Nov 29, 2013 at 1:14

3 Answers 3

1

You need to do a few steps to achieve this

// Construct a temporary list.
List<Double> ell = new ArrayList<Double>();
// iterate our input array 'a'.
for (double d : a) {
  // test if the value 'd' is greater then the threshold 'x'.
  if (d > x) {
    // if it is, add it to the temporary list.
    ell.add(d);
  }
}
// construct an array of double(s).
double[] r = new double[ell.size()];
for (int i = 0; i < r.length; i++) {
  // Add the element(s) to the output array.
  r[i] = ell.get(i);
}
return r; // Return the Array.
Sign up to request clarification or add additional context in comments.

Comments

0
public static Double[] threshold(double[] a, double x){
    List<Double> l = new ArrayList<Double>(a.length);
    for( double d : a)
        if( d > x )
            l.add(d);

    return l.toArray(new Double[0]);
}

A couple things:

  1. Generics (<>) only except classes not primitives so you need to use Double not double.
  2. You need a for loop to iterate through each item in a
  3. You can use toArray() to convert to type Double[] (assuming you can change your return type). Otherwise you need to do what @Elliott suggests, and create a new double[] with a for-loop.

Comments

0

I would do it this way

public static double[] threshold(double[] a, double x) {
    int n = 0;
    for (double e : a) {
        if (e > x) {
            n++;
        }
    }
    double[] a2 = new double[n];
    n = 0;
    for (double e : a) {
        if (e > x) {
            a2[n++] = e;
        }
    }
    return a2;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.