简体   繁体   中英

JAVA: Passing an array to a method

I can't seem to pass my array to a secondary method. It only sees one of the 10 inputs, so I can't properly use it in the secondary method.

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; 
}

variable i is never being changed so you are assigning each new number to the same spot in the array overwriting the previous number.

Just use your n variable instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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