【问题标题】:JAVA: Passing an array to a methodJAVA:将数组传递给方法
【发布时间】:2015-04-13 22:54:18
【问题描述】:

我似乎无法将我的数组传递给辅助方法。它只看到 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; 
}

【问题讨论】:

  • 如果你使用 for 循环来填充 numbers 数组会更好,因为你知道会有多少次迭代。

标签: java arrays methods


【解决方案1】:

在第一个while循环中,变量i没有变化。

【讨论】:

    【解决方案2】:
    while (n < numbers.length) { 
        numbers[i] = input.nextDouble(); 
        n+=1; 
    }
    

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

    只需使用您的 n 变量即可:

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

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2021-06-04
      • 2013-10-04
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多