Java实现从键盘获取一串数字并按降序排列
时间: 2024-05-15 12:17:06 浏览: 145
可以使用Java的Scanner类来实现从键盘获取一串数字,并通过Arrays类的sort方法按降序排列。下面是示例代码:
```java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一串数字,以空格分隔:");
String input = scanner.nextLine();
String[] numbers = input.split(" ");
int[] ints = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
ints[i] = Integer.parseInt(numbers[i]);
}
Arrays.sort(ints);
System.out.println("按升序排列:" + Arrays.toString(ints));
for (int i = 0; i < ints.length / 2; i++) {
int temp = ints[i];
ints[i] = ints[ints.length - i - 1];
ints[ints.length - i - 1] = temp;
}
System.out.println("按降序排列:" + Arrays.toString(ints));
}
}
```
当然,你也可以使用Collections类的sort方法来对字符串数组进行降序排列,代码如下:
```java
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一串数字,以空格分隔:");
String input = scanner.nextLine();
String[] numbers = input.split(" ");
Arrays.sort(numbers);
Collections.reverse(Arrays.asList(numbers));
System.out.println("按降序排列:" + Arrays.toString(numbers));
}
}
```
其实两种方法的结果是一样的,只是用到的类不同而已。
阅读全文