0

I have made some code which gets numbers from the standard input and I want to take these values and sort them in ascending order. How do I do it?

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...");
        }



    }
}

Sorry if I am posting a question that has already been answered but I could not find any answers which seemed to work with my code :(

joragupra
  • 692
  • 1
  • 12
  • 23

3 Answers3

1

Just sort the ArrayList:

Collections.sort(numbers);
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Collections.sort(numbers); should do the trick

TheEwook
  • 11,037
  • 6
  • 36
  • 55
  • You're welcome. BTW, it's a good practice to accept answers if they've helped you ;) – TheEwook Mar 14 '14 at 19:18
  • Oh that's weird... I'm pretty sure last time I tried accepting the answer it said I didn't have a high enough reputation (I'm completely new to Stackoverflow) and it hasn't gone up since... I don't know... –  Mar 15 '14 at 22:39
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);
    }
}
Farvardin
  • 5,336
  • 5
  • 33
  • 54