在数组中搜索特定值

时间:2016-04-04 14:44:54

标签: java

所以这就是我的困境,我正在尝试搜索一个特定值的数组,但是我收到的错误是我不知道如何修复。这是我目前的代码:

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

我收到的错误消息如下:

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

对此的任何帮助将不胜感激!提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用Java 8执行此操作:

<div class="col-md-3">
    <a href="http://codepen.io/ArnaudBalland/pen/ogoMvd">
      <div class="vidfill">
      </div>
      <video width="320" height="240" autoplay loop class="login">
        <source src="images/loginfade.mp4" type="video/mp4"> Your browser does not support the video tag.
      </video>
    </a>
  </div>

它将您的double数组转换为DoubleStream。然后它将流与谓词相匹配,例如说我等于10.0。

我希望它有所帮助。

答案 1 :(得分:0)

你应该知道的是Java中的数组没有方法contains()。 你可以做的是循环数组并比较元素。