我这里有一个程序,允许用户输入数字(n),程序输出'n'随机数。我需要创建一个循环来组织从最低到最大的这些随机值,但我不确定如何去做,任何想法?谢谢,
// 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");
}
我将信息(随机n值)存储在数组中,以便稍后调用它们。
答案 0 :(得分:3)
使用TreeSet
等数据结构自动将数据保存在排序顺序中。
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);
}
按降序输出数字
// Descending order
for (Integer i: randomSet.descendingSet()) {
System.out.println(i);
}
答案 1 :(得分:2)
Java具有内置排序功能:
// 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");
}
答案 2 :(得分:1)
您可以将它们放入arraylist并定义自己的Comparator来对它们进行排序。例如。
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());
您只需要定义一个新的比较器
public class MyCustomComparator implements Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
//say I want descending order
return -1* o1.compare(o2);
}
}
但你可以根据需要对其进行排序。如果你想要考虑当前值o1,小于o2,如果它们被认为是相等则返回0,或者如果大于你的if语句条件,则确保它返回-1。