use*_*848 4 java sorting for-loop bubble-sort
我试图排序一些用空格分隔的用户输入的整数.
输入:4 2 1 5 9 - 预期输出:1 2 4 5 9
用户在循环中按下回车后我无法弄清楚如何停止循环,其中i <num.当我逐个输入整数时,我的代码会起作用.任何帮助,将不胜感激
class javasort {
public static void main(String[] args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
// System.out.println("Enter the number of integers to sort:");
// num = input.nextInt();
num = 5; // <-- the user input should be dynamic
int array[] = new int[num];
System.out.println("Enter integers: ");
for (i = 0; i < num; i++)
array[i] = Integer.parseInt(input.next());
num = i; // make array as big as input ?
for (i = 0; i < (num - 1); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}}
Run Code Online (Sandbox Code Playgroud)
你的代码几乎是正确的,然后你删除了你的最佳提示.用Scanner.nextInt()得像
num = input.nextInt(); // <-- get the count.
int array[] = new int[num];
System.out.println("Enter integers: ");
for (i = 0; i < num; i++) { // <-- don't rely on indentation for flow control.
array[i] = input.nextInt(); // <-- get a number "num" times.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |