有 Java 编程相关的问题?

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

java如何让用户按降序输出?

我试过使用Arrays.sort(int, Collections.reverseOrder()); 但这似乎不起作用。我试图按降序得到输出。它必须在for循环中吗?或者在我最后使用的System.out.print()

public class EmployeeWorkHours {
    public static void main(String[] args) {

          Scanner turtle = new Scanner(System.in);
          String[] calender = { "S", "M", "T", "W", "Th", "F", "S" };
          System.out.println("How many Employee's do you have?: ");
          int NUMBER_OF_EMPLOYEES = turtle.nextInt();
          turtle.nextLine();

          int [][]hours;
          int[] totalHours= new int[NUMBER_OF_EMPLOYEES];

          hours = new int[NUMBER_OF_EMPLOYEES][7];
          String[] employee = new String[NUMBER_OF_EMPLOYEES];

          // input for Names
          for (int x = 0; x < (employee.length); x++) {
              System.out.println("Name of Employee " + (x + 1) + ": ");
              String name = turtle.nextLine();
              employee[x] = name;

          }
          // input for Hours
          for (int z = 0; z < employee.length; z++) {
              System.out.println("Starting from Sunday, enter the hours Employee "+ (z + 1)+ " has worked each day (Make sure you seperate it by spaces): ");
              for (int a = 0; a < 7; a++) {
                  hours[z][a] = turtle.nextInt();
              }
              turtle.nextLine();
          }
          // Print everything out
          for (int i = 0; i < employee.length; i++) {
              totalHours[i]=0;
              for(int j=0; j<7; j ++){
                  totalHours[i] = totalHours[i]+hours[i][j];   
              }

              System.out.println("Employee " + (i + 1) +" worked " + totalHours[i] + " hours");          
          }
     }
}

共 (2) 个答案

  1. # 1 楼答案

    试一试

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

    Collections.sort(list);
    Collections.reverse(list);
    

    它还取决于您正在使用的集合的实现

  2. # 2 楼答案

    试试看 this

    更具体地说,这是链接的一部分

      Comparator cmp = Collections.reverseOrder();  
    
       // sort the list
       Collections.sort(list, cmp);  
    
       System.out.println("List sorted in ReverseOrder: ");      
       for(int i : list){
            System.out.println(i+ " ");
       }