我在這個論壇上搜索有人遇到類似於我的問題,我無法找到爲什麼地球上我的程序不能正常工作,除了看起來堅實。我剛剛開始學習Java,所以我不確定這裏是否有某種語法錯誤,或者更多,但我一直在盯着它,而這個網站在過去的一個小時裏,我沒有看到怎麼了。陣列沒有正確初始化
public class BubbleSort {
public static void main(String[] args) {
int a, b, n, change, i, operations, choice;
Scanner input = new Scanner(System.in);
System.out.println("Would you like to add your own numbers?");
System.out.println("enter '1' for no and '2' for yes");
choice = input.nextInt();
if (choice == 1) {
int[] array = {
5,
7,
3,
9,
1,
0,
6
};
n = 7;
} else if (choice == 2) {
System.out.println("How many numbers would you like to add to the" +
"Array? (Add up to 10)");
n = input.nextInt();
int array[] = new int[n];
System.out.println("Input " + n + " integers");
for (a = 0; a < n; a++) {
array[a] = input.nextInt();
}
}
System.out.println("Bubble Sort operation:");
for (a = 0; a < (n - 1); a++) {
System.out.print("iteration " + (a + 1) + ": ");
for (b = 0; b < n - a - 1; b++) {
if (array[b] > array[b + 1]) {
change = array[b];
array[b] = array[b + 1];
array[b + 1] = change;
operations++;
}
}
for (i = 0; i < n; i++) {
System.out.print(array[i]);
}
System.out.println();
}
System.out.print("Finished array after bubble sort: ");
for (i = 0; i < n; i++) {
System.out.print(array[i]);
}
System.out.println();
System.out.println("This operation took " + operations + " cycles");
System.out.println();
}
}
這只是一個簡單的泡沫排序程序,但我在這裏嚴重難住。任何想法會有什麼錯誤?錯誤說n
從不初始化。
你得到的錯誤是什麼? – haihui
這是說n沒有被初始化 –
另外,它沒有認識到循環中的數組與if語句中初始化的數組相同 –