The following rewriting should be instructive:
public class Delete {
static int search(int key, int[] arr) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == key) {
return i;
}
return -1;
}
static void print(int[] arr, final int L) {
for (int i = 0; i < L; i++) {
System.out.println(arr[i]);
// try this also:
// System.out.format("%02d ", arr[i]);
}
}
public static void main(String[] args) {
int nums[] = { 77, 99, 44, 11, 00, 55, 66, 33, 10 };
final int N = nums.length;
int searchKey = 55;
int pos = search(searchKey, nums);
for (int t = pos; t < N-1; t++) {
nums[t] = nums[t + 1];
}
print(nums, N-1);
// prints 77, 99, 44, 11, 0, 66, 33, 10
System.out.println(010 == 8); // prints "true"
System.out.println(00000); // prints "0
}
}
Here are some key observations:
- Break apart logic into helper methods. This makes the logical components easier to test and reuse, and the overall logic easier to understand.
- It makes the code easier to understand if you use
final
local variables like N
to denote the initial size of int[] nums
, and define the rest of the logic in terms of N
, N-1
, etc.
- The more non-
final
variables there are, the harder it is to understand what's going on as their values changes over time
- Follow coding convention. In particular, class names starts with uppercase.
- Do be careful with the
00
in the array. The 0
prefix is for octal literals. That is, 010 == 8
.
- Do note that
00
is printed as simple 0
. Numerically, 00 = 000 = 0000 = 0
. If you need this to be zero-padded, then that's a formatting issue.
See also
On octal literals
On zero-padding