如何在Java中的arraylist中按升序排列数字?

时间:2014-03-12 16:10:41

标签: java

我已经制作了一些从标准输入中获取数字的代码,我想获取这些值并按升序对它们进行排序。我该怎么做?

import java.util.*;

public class Main {

    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        boolean Done = false;
        ArrayList<Integer> numbers = new ArrayList<Integer>(20);


        while(Done == false){
            System.out.print("Enter number: ");
            int x = sc.nextInt();
            numbers.add(x);

            System.out.print("Keep going? (Y/N)");
            String keepGoing = sc.next();

            if(keepGoing.equalsIgnoreCase("Y"))
                ;
            else if(keepGoing.equalsIgnoreCase("N")){
                Done = true;

                                //this is just temporary to print out the numbers.
                                for(int n : numbers){
                    System.out.print(n + " ");
                }
            }
            else
                System.out.println("Command not recognised...");
        }



    }
}

很抱歉,如果我发布的问题已经得到解答,但我找不到任何似乎与我的代码相符的答案:(

3 个答案:

答案 0 :(得分:1)

ArrayList只需sort

Collections.sort(numbers);

答案 1 :(得分:1)

Collections.sort(numbers);应该做的伎俩

答案 2 :(得分:0)

import java.util.*;

public class Main {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        boolean Done = false;
        ArrayList<Integer> numbers = new ArrayList<Integer>(20);
        while (Done == false) {
            System.out.print("Enter number: ");
            int x = sc.nextInt();
            numbers.add(x);

            while (true) {
                System.out.print("Keep going? (Y/N) :");
                String keepGoing = sc.next();
                if (keepGoing.equalsIgnoreCase("Y"))
                    break;
                else if (keepGoing.equalsIgnoreCase("N")) {
                    Done = true;
                    break;
                }
                System.out.println("Command not recognised...");
            }
        }

        System.out.println("before sort : " + numbers);
        Collections.sort(numbers);
        System.out.println("after sort : " + numbers);
    }
}