用户可以输入尽可能多的号码,程序应该对它们进行排序。所以我想在开始排序之前找到输入中的数字元素。示例“输入一些数字”输入:76 24 56 9 312 1 3013我想要输出:1 9 24 56 76 312 3013(升序)。注意我没有要求用户输入他将要输入的数量,这正是我想知道如何找到的。
这是工作代码,用户自己输入数组大小
import java.util.Scanner;
public class ArraySorting {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter size of the array");
int z = in.nextInt();
int a[] = new int[z];
System.out.println("Enter numbers");
for (int i = 0; i < z; i++) {
a[i] = in.nextInt();
}
for (int j = 0; j < z - 1; j++) {
for (int p = 0; p < (z - 1) - j; p++) {
if (a[p] > a[p + 1]) {
int n = a[p];
a[p] = a[p + 1];
a[p + 1] = n;
}//if loop
}//for loop 2
}//for loop 1
System.out.println("Numbers in Ascending order:");
for (int k = 0; k < z; k++) {
System.out.print(a[k] + " ");
}
}
}
答案 0 :(得分:0)
您可以将输入作为逗号分隔的数字。使用逗号分割它,排序并打印输出。
而不是数组使用List。用户将继续输入一个号码。如果用户输入&#34;结束&#34;或者&#34;完成&#34;或者其他什么,然后你排序列表并打印输出。
答案 1 :(得分:0)
在每个号码后点击返回。
为了将来请使用有意义的变量名称,为其他开发人员阅读代码有很多帮助:)
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input;
boolean finished = false;
System.out.println("Enter numbers.\nType End to finish");
do {
input = scanner.next();
if (input.toLowerCase().equals("end")) {
finished = true;
Collections.sort(numbers);
System.out.println(numbers);
System.out.println("You have entered " + numbers.size() + " numbers");
} else {
try {
numbers.add(Integer.parseInt(input));
}catch(Exception e){
System.out.println("This is not a number please try again !");
}
}
} while (!finished);
}