【发布时间】:2021-06-14 11:47:44
【问题描述】:
我正在编写代码,输入数组长度和数组中的项目,然后使用冒泡排序方法将数组中的项目按顺序排列。
这是所需的输入输出
Enter the number of items in array:
5
Enter the items:
5
6
4
2
3
The sorted array is:
2
3
4
5
6
我遇到的问题是该方法似乎没有读取用户的输入。
这是我的代码
import java.util.Scanner;
public class Main {
private static int[] array;
public static void main(String[] args) {
int arrayLength;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in array: ");
arrayLength = scanner.nextInt();
int[] array = new int[10];
System.out.println("Enter the items: ");
for (int i = 0; i < arrayLength; i++) {
array[i] = scanner.nextInt();
}
bubbleSort();
}
public static void bubbleSort() {
int i, j, temp;
boolean swap;
for (i = 0; i < array.length - 1; i++) {
swap = false;
for (j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swap = true;
}
}
if (swap == false)
break;
}
System.out.print("The sorted array is: ");
for (i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
System.out.println();
}
}
}
【问题讨论】:
标签: java arrays loops methods bubble-sort