我正在尝试编写一些代码,允许用户输入许多数字,然后将它们放入列表中,然后对它们进行升序排序,然后再降序排列。
这是我的 Java 代码:
public static void questionThree() throws java.lang.Exception {
int input1;
int input2;
int input3;
int noAmount;
List<Integer> numberList = new ArrayList<Integer>();
Scanner user_input = new Scanner( System.in );
System.out.println("Enter the amount of numbers: ");
noAmount = user_input.nextInt();
for (int i = 0; i < noAmount; i++) {
System.out.println("Enter a number: ");
input2 = user_input.nextInt();
numberList.add(input2);
}
Arrays.sort(numberList);
for (int i = 0; i < numberList.size(); i++) {
System.out.println(numberList.get(i));
}
}
控制台提示我不能在这里使用排序。
如何对刚刚放入列表中的整数进行排序?
最佳答案
Arrays.sort(numberList);
那个排序函数将数组作为输入而不是集合。您正在使用 Arrays
类,该类用于对数组而不是 Collections
进行排序。
你应该使用
Collections.sort(numbersList);
因为你想倒序排列列表
Collections.sort(list, Collections.reverseOrder());
关于java - 尝试根据用户输入对列表中的整数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32887125/