输入20个数,以数组的形式存放,将这20个数按递减顺序排序后输出 java并且使用循环
时间: 2024-10-18 20:08:17 浏览: 29
在Java中,你可以使用ArrayList或者直接创建一个整型数组来存储20个数,并通过遍历和比较的方式来实现递减排序。这里是一个简单的示例,展示了如何使用Arrays类的sort方法结合自定义Comparator来达到这个目的:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 创建一个长度为20的整型数组
int[] numbers = new int[20];
// 提示用户输入20个数并存入数组
for (int i = 0; i < numbers.length; i++) {
System.out.print("请输入第" + (i+1) + "个数:");
numbers[i] = Integer.parseInt(System.console().readLine());
}
// 使用Arrays.sort()对数组进行排序,传入自定义的Comparator使得降序排列
Arrays.sort(numbers, Collections.reverseOrder());
// 输出排序后的数组
System.out.println("按照递减顺序排序后的数组:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
```
在这个程序中,我们首先获取用户输入的20个数字,然后使用`Arrays.sort()`方法对它们进行排序,同时传递一个`Collections.reverseOrder()`对象作为比较器,使得数组元素按照降序排列。最后,我们遍历并打印出排序后的数组。
阅读全文
相关推荐


















