-3

如果有更好的方法来做到这一点,我会很乐意倾听。我想创建一个具有用户输入大小的数组。目前,我可以让所有用户将数据输入数组的唯一方法。但我想让该方法允许找到中位数,所以即使它们是零,我也不能拥有这些额外的数字。

import java.util.Scanner;

public class Test {
    static double total;
    static String nums;
    static String[] numsa;
    static double[] numda = {5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5};
    static int size;
    static Scanner s = new Scanner(System.in);

    public static void main(String[] args) {

        System.out.print("Please input data with a space between each digit: ");
        nums = s.nextLine();
        numsa = nums.split("\\s+");
        size = numsa.length;

        for (int i = 0; i < size; i++) {
            total += (Double.parseDouble(numsa[i]));
        }

            for (int i = 0; i < size; i++) {
                numda[i] = Double.parseDouble(numsa[i]);
                System.out.println("Num Double Array[" + i + "] = " + numda[i]); 
        }   
        System.out.println("Total: " + total);  
    }
}
4

1 回答 1

2

After getting size you can do

numda = new double[size];

to create an array of length size.

See the docs at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html.

于 2013-09-20T17:50:41.257 回答