Reputation: 11
I have a program here that allows an user to input a number (n) and the program outputs 'n' random numbers. I need to create a loop that organizes these random values from lowest to largest, but I am unsure how to go about doing that, any ideas? Thanks,
// takes inputted value to "randomize" numbers too
int amtOfNumbers = Integer.parseInt(amtOfNumbersField.getText());
int[] random = new int[amtOfNumbers-1]; // 1 prevents array from including 0
Random r = new Random(); //for random values
// Insert random numbers into the array
for (int i = 0; i < random.length; i++) {
random[i] = r.nextInt(100) + 1;
}
// Output random numbers
for (int i = 0; i < random.length; i++) {
itsATextArea.append(random[i] + "\n");
}
I stored the information (random n values) in the array so I can call them out later.
Upvotes: 0
Views: 1999
Reputation: 4102
You can put them into an arraylist and define your own Comparator to sort them. For example.
int amtOfNumbers = Integer.parseInt("10");
ArrayList<Integer> randomList= new ArrayList<Integer>();
Random r = new Random(); //for random values
// Insert random numbers into the set
for (int i = 0; i < amtOfNumbers; i++) {
randomList.add(r.nextInt(100) + 1);
}
//Now sort it however way you want
Collections.sort(randomList, new MyCustomComparator());
All you need is to define a new comparator
public class MyCustomComparator implements Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
//say I want descending order
return -1* o1.compare(o2);
}
}
but you can sort it however you want. Just make sure it returns -1 if you want to consider the current value o1, less than o2, return 0 if they are to be considered equal, or 1 if greater than based on your if statement conditions.
Upvotes: 1
Reputation: 51711
Use a data structure like TreeSet
to keep your data in sorted order automatically.
int amtOfNumbers = Integer.parseInt("10");
TreeSet<Integer> randomSet = new TreeSet<Integer>();
Random r = new Random(); //for random values
// Insert random numbers into the set
for (int i = 0; i < amtOfNumbers; i++) {
randomSet.add(r.nextInt(100) + 1);
}
// Output in Ascending order
for (Integer i: randomSet) {
System.out.println(i);
}
To output the numbers in descending order
// Descending order
for (Integer i: randomSet.descendingSet()) {
System.out.println(i);
}
Upvotes: 3
Reputation: 78650
Java has built-in sort capability:
// Insert random numbers into the array
for (int i = 0; i < random.length; i++) {
random[i] = r.nextInt(100) + 1;
}
Arrays.sort(random);
// Output random numbers
for (int i = 0; i < random.length; i++) {
itsATextArea.append(random[i] + "\n");
}
Upvotes: 2