java试图根据用户输入对列表中的整数进行排序
我正在尝试编写一些代码,允许用户输入许多数字,然后将它们放入一个列表中,然后对它们进行升序和降序排序
以下是我的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));
}
}
控制台抱怨我不能在这里使用排序
如何对刚刚放入列表的整数进行排序
# 1 楼答案
您应该使用^{} 而不是^{} ,因为您是在对集合而不是数组进行排序:
关于代码的其他评论:
user_input
应该重命名为userInput
李>input1
和input3
李>input2
只在循环内部需要,因此可以写入int input2 = userInput.nextInt();
并在方法开头删除其声明李># 2 楼答案
该排序函数将数组作为输入,而不是集合。您正在使用
Arrays
类,该类用于对数组进行排序,而不是Collections
你应该使用
因为你想按相反的顺序排序