gpt4 book ai didi

java - 在数组中搜索特定值

转载 作者:行者123 更新时间:2023-12-01 10:06:37 28 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以使用 Java 8 来做到这一点:

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

它将 double 组转换为 DoubleStream。然后,它将流与谓词进行匹配,例如 i 等于 10.0。

希望对您有所帮助。

关于java - 在数组中搜索特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405836/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com