Hello! I am currently engaged in the book "Data Structures and Algorithms in Java" by Robert Lafore. There is an example for removing an element from an array by a given value. (p.54)
It looks like this:
public class ArrayApp { public static void main(String[] args) { long[] arr; //ΡΡΡΠ»ΠΊΠ° Π½Π° ΠΌΠ°ΡΡΠΈΠ² arr = new long[100]; //ΡΠΎΠ·Π΄Π°Π½ΠΈΠ΅ ΠΌΠ°ΡΡΠΈΠ²Π° int nElems = 0; //ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² int j; //ΡΡΠ΅ΡΡΠΈΠΊ ΡΠΈΠΊΠ»Π° long searchKey; //ΠΊΠ»ΡΡΠΈ ΠΈΡΠΊΠΎΠΌΠΎΠ³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ° // Π²ΡΡΠ°Π²ΠΊΠ° 10 ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² 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; nElems = 10; //ΠΌΠ°ΡΡΠΈΠ² ΡΠΎΠ΄Π΅ΡΠΆΠΈΡ 10 ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² // Π²ΡΠ²ΠΎΠ΄ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² for (j = 0; j < nElems; j++) System.out.print(arr[j] + " "); System.out.println(""); searchKey = 55; //ΡΠ΄Π°Π»Π΅Π½ΠΈΠ΅ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ° Ρ ΠΊΠ»ΡΡΠΎΠΌ 55 for (j = 55; j < nElems; j++) //ΠΏΠΎΠΈΡΠΊ ΡΠ΄Π°Π»ΡΠ΅ΠΌΠΎΠ³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ° if (arr[j] == searchKey) break; for (int k = j; k < nElems - 1; k++) //ΡΠ΄Π²ΠΈΠ³ ΠΏΠΎΡΠ»Π΅Π΄ΡΡΡΠΈΡ
ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² arr[k] = arr[k + 1]; nElems--; //ΡΠΌΠ΅Π½ΡΡΠ΅Π½ΠΈΠ΅ ΡΠ°Π·ΠΌΠ΅ΡΠ° for (j = 0; j < nElems; j++) //Π²ΡΠ²ΠΎΠ΄ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² System.out.print(arr[j] + " "); System.out.println(""); } }
Ideally, the answer should be:
77 99 44 55 22 88 11 0 66 33
77 99 44 22 88 11 0 66 33
In fact, the program now works like this:
77 99 44 55 22 88 11 0 66 33
77 99 44 55 22 88 11 0 66
That is, it simply deletes the last element of the array instead of the specified value.
How should it be to write a cycle so that it works correctly?