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 :(
Collections.sort(numbers);
should do the trick
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);
}
}
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.