0

So here's my dilemma, I'm trying to search an array for a specific value, but I'm getting an error that I don't know how to fix. Here's my current code:

import java.util.Arrays;

public class Marathon {

public static void main(String[] args)  {

    double[]    weeks = {2,4.66,7.33,10,12.66,15.33,18,20.66,23.33,26};
    double sum = 0;
    int length = weeks.length;

    for (double i : weeks)
        sum += i;

    System.out.println("What is the value for array element 2: " + weeks[1]);
    System.out.println("What is the list length: " + length);
    System.out.println("Sum of all miles run during the 10 week period: " + sum);
    System.out.println("Does the list contain a week with 4 miles: ");

    boolean retval = weeks.contains(4.00);
    if (retval == true) {
        System.out.println("10 is contained in the list");
       }
      else {
        System.out.println("10 is not contained in the list");
       }
    }
}

The error message I'm getting is as follows:

Cannot invoke contains(double) on the array type double[]   
Marathon.java/do while/src  line 18 Java Problem

Any help on this would be greatly appreciated! Thanks in advance.

2 Answers2

1

You could do this with Java 8:

boolean retval = DoubleStream.of(weeks).anyMatch(i->i==10.0);

It transforms your array of double to DoubleStream. Afterwards it matches the stream against a predicate saying that i equals 10.0 for example.

I hope it helps.

joel314
  • 1,060
  • 1
  • 8
  • 22
0

What you should know is that array in Java does not have method contains(). What you can do is to loop the array and compare the elements.

Reed Grey
  • 508
  • 6
  • 10