繁体   English   中英

JAVA:将数组传递给方法

[英]JAVA: Passing an array to a method

我似乎无法将我的数组传递给辅助方法。 它只能看到10个输入中的一个,所以我无法在辅助方法中正确使用它。

public static void main(String[] args) {
    java.util.Scanner input = new java.util.Scanner(System.in);
    System.out.println("Enter some numbers: ");
    double [] numbers = new double [10]; 
    int n = 0; 
    int i = 0;
    while(n < numbers.length) { 
        numbers[i] = input.nextDouble(); 
        n+=1; 
    }
    System.out.println(min(numbers));
} 

public static double min(double[] array) { 
    System.out.println(array[1]);
    double smallest = array[0];
    for (int l = 1; l < array.length; l++) { 
        if (array[l] < smallest) { 
            smallest = array[l]; 
            System.out.println("Your smallest = " + smallest);
        }

    }
    return 0; 
}

在第一个while循环中,变量i不会改变。

while (n < numbers.length) { 
    numbers[i] = input.nextDouble(); 
    n+=1; 
}

变量i永远不会被更改,因此您将每个新数字分配给数组中的同一位置,覆盖前一个数字。

只需使用你的n变量:

while (n < numbers.length) { 
    numbers[n] = input.nextDouble(); 
    n += 1; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM