我寫了這段代碼來找到一個數組中的元素,它工作得很好,但我不明白它是如何工作的100%。我的問題是,如何從(j == nElems)只運行從0到9?我也注意到,當沒有找到搜索關鍵字時,條件在for循環之外得到滿足。爲什麼這個條件滿足? (j == nElems)
public class ArrayApp {
public static void main(String args[]) {
int nElems = 10;
int[] arr = new int[nElems];
int j;
int searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
//Find 66 in array
searchKey = 66;
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
if (j == nElems) {
System.out.println("Cant find " + searchKey);
} else {
System.out.println("Found " + searchKey + " in position " + j);
}
//Remove 55 from array
searchKey = 55; // delete item with key 55
for (j = 0; j < nElems; j++) { // look for it
if (arr[j] == searchKey) {
break;
}
}
for (int k = j; k < nElems - 1; k++) { // move higher ones down
arr[k] = arr[k + 1];
}
nElems--;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
}
}
是否有任何理由你沒有調試應用程序? – liorsolomon