java用户随机输入若干数(从用户输入开始到随机停止输入为止),然后将这些数排序输出。(用字符串和数组处理)
时间: 2024-05-12 11:21:16 浏览: 4
下面是Java代码实现:
```java
import java.util.*;
public class SortNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("请输入一些整数,以任意非数字字符结束输入:");
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
Collections.sort(list);
System.out.println("排序结果为:" + list);
}
}
```
这里使用了Scanner类来从控制台获取用户输入的整数,并将它们存储在一个ArrayList中。然后使用Collections.sort方法对列表进行排序,并输出排序结果。注意,输入时可以使用任意非数字字符来结束输入,例如输入一个空格或者回车键。
相关问题
java用户随机输入若干数(从用户输入开始到随机停止输入为止),然后将这些数排序输出。(用字符串和数组处理)
好的,我明白你的问题了。以下是实现这个功能的代码示例:
```java
import java.util.*;
public class SortNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
// 读取用户输入的数字,直到输入非数字为止
System.out.println("请输入数字,输入非数字将停止输入:");
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
numbers.add(number);
}
// 将数字排序并输出到控制台
Collections.sort(numbers);
System.out.println("排序后的数字为:" + numbers.toString());
}
}
```
这个程序首先创建了一个 Scanner 对象来读取用户的输入。然后,它循环读取用户输入的数字并将它们添加到一个动态数组中,直到用户输入非数字为止。接下来,使用 Collections 类中的 sort 方法对数组进行排序,并将排序后的结果转换为字符串并输出到控制台。
注意,这里使用了动态数组而不是传统的静态数组,因为我们不知道用户要输入多少个数字。另外,在实际开发中,我们可能需要添加一些代码来处理用户可能输入的错误和异常情况。
Java用户随机输入若干数(从用户输入开始到随机停止输入为止),然后将这些数排序输出。(用字符串和数组处理)
好的,这是一个关于Java的问题。您可以使用Scanner类获取用户输入的数值,并将它们存储在数组中。然后,您可以使用Arrays类的sort()方法将数组排序,并使用循环打印排序后的数组元素。以下是示例代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> nums = new ArrayList<>();
System.out.println("请输入数字,输入0表示结束输入:");
int num = input.nextInt();
while(num != 0) {
nums.add(num);
num = input.nextInt();
}
Integer[] arr = nums.toArray(new Integer[0]);
Arrays.sort(arr);
System.out.println("排序后的数字为:");
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
希望对您有所帮助!接下来,您还有其他问题吗?