簡體   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