有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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));
    }
}

控制台抱怨我不能在这里使用排序

如何对刚刚放入列表的整数进行排序


共 (2) 个答案

  1. # 1 楼答案

    您应该使用^{}而不是^{},因为您是在对集合而不是数组进行排序:

    Collections.sort(numberList);
    

    关于代码的其他评论:

    • 您应该遵守Java命名约定:user_input应该重命名为userInput
    • 您正在声明未使用的变量:input1input3
    • 你应该尽量缩小每个变量的范围。由于input2只在循环内部需要,因此可以写入int input2 = userInput.nextInt();并在方法开头删除其声明
  2. # 2 楼答案

     Arrays.sort(numberList);
    

    该排序函数将数组作为输入,而不是集合。您正在使用Arrays类,该类用于对数组进行排序,而不是Collections

    你应该使用

    Collections.sort(numbersList);
    

    因为你想按相反的顺序排序

    Collections.sort(list, Collections.reverseOrder());