使用数组Java中的用户输入对数字进行排序

时间:2015-03-23 01:34:32

标签: java arrays sorting

我是java的初学者,我有一个希望简单的问题。 我可以按顺序获取数字,但只有一定数量的数字被添加到数组中。当数字小于最小数字时,它将替换最小数字(前一个最小数字从数组中删除)。我可以做些什么来填充所有阵列点?

public class apples {
    public static void main(String[] args) {
        System.out.print("How many numbers: ");
        int num=IO.readInt();
        double array[]=new double[num];
        double temp;
        boolean fixed=false;

        while (fixed==false){
            fixed=true;

            for(int j=0; j<num;j++){
                double x = IO.readDouble();
                array[j] = x;

                for (int i = 0; i < ( num - 1 ); i++) {
                    for (j = 0; j < num - i - 1; j++) {
                        if (array[j] > array[j+1]) {
                            temp = array[j];
                            array[j] = array[j+1];
                            array[j+1] = temp;
                            fixed=false;
                         }
                    }
                }

                System.out.println("Sorted list of integers:");
                for (int i = 0; i < num; i++) 
                    System.out.println(array[i]);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

首先读取数字,然后对数组进行排序(它是double而不是int的数组。像,

public static void main(String[] args) {
    System.out.print("How many numbers: ");
    int num = IO.readInt();
    double array[] = new double[num];
    for (int j = 0; j < num; j++) {
        System.out.printf("Please enter double %d:%n", j + 1);
        array[j] = IO.readDouble();
    }
    System.out.println("unsorted array: " + Arrays.toString(array));
    Arrays.sort(array); // <-- or however you want to sort the array.
    System.out.println("sorted array: " + Arrays.toString(array));
}

答案 1 :(得分:0)

public static void main(String[] args) {
        System.out.print("How many numbers: ");
        int num = IO.readInt();
        double array[] = new double[num];
        for (int i = 0; i < num; i++) {
            System.out.print("["+i+"]Please enter your double");
            array[i] = IO.readDouble();
        }

        //Sort
        double temp = 0;
        for (int i = 0; i < num - 1; i++) {
            for (int j = i + 1; j < num ; j++) {
                if (array[j] > array[j]) {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                 }
            }
        }

        //Result
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
    }