java - 如何查找一个数字是否在数组中?

标签 java if-statement for-loop methods boolean

尝试编写一种方法来告诉我一个数字是否在数组中。到目前为止我有..

    public static boolean inList(double number, double[] list){
    for (double i : list)
        {
            if (i == number){
                return false;
        }

    }
    return true; //if its not in the array I want the if statement to run.
}

到目前为止,这对我没有用,出于某种原因,它无法识别数组中是否包含某些数字。

最佳答案

您混淆了 return 语句。应该是这样的:

    public static boolean inList(double number, double[] list){
        for (double i : list)
        {
            if (i == number){
                //return true when you've found the match!
                return true;
            }
        }
    //return false here because you finished looking at the entire array 
    //and couldn't find a match.
    return false;
}

关于java - 如何查找一个数字是否在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21563040/

相关文章:

java - 连接池中的最佳连接数

java - 使用字符串的 IF 语句

java - 在Java中获取相对内部类名称

java - java中任意数量组件的元组类

Java Thread.sleep 泄漏线程?

php - 如何从 smarty 模板中的 URL 访问变量值?

if-statement - 检查 PyGame 混合器 channel 是否正在播放声音

java - 在程序中添加 for 循环时遇到问题

c - 递增嵌套数组 - 带有日期信息

javascript - 循环遍历json对象并将其放入html表中