I am writing a program that will take user input and sort it in ascending order or descending order depending on what they choose. I tried using a simple array but it didn't work properly with the array sort methods so I then tried an ArrayList. This seems to work except for the fact that it only reads the first int that is typed by the user. I tried the addAll method but it appears that only works for collections and not variables.
This is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class ElevenThree {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<Integer>();
int size = 0;
int type = scan.nextInt();
if(type == 0) {
size = scan.nextInt();
arrayList.add(scan.nextInt());
Collections.sort(arrayList);
}
if (type == 1) {
size = scan.nextInt();
arrayList.add(scan.nextInt());
Collections.sort(arrayList, Collections.reverseOrder());
}
System.out.println(arrayList);
}
}
Input:
0
9
4 3 6 8 9 2 1 5 7
Output:
[4]
By the way, I have the size variable there because this is an assignment through a program that automatically inputs the size variable so it needs to be there even if it doesn't affect the program in any way.