I tried to insert a character into the array in the code below, it works but gets rid of the number in the position. How do I move the old element back a space.
public class MainArrays {
public static int[] add(int[] arr, int val) {
int[] newArray = Arrays.copyOf(arr, arr.length 1);
newArray[arr.length] = val;
return newArray;
}
public static int[] del(int[] arr) {
return Arrays.copyOf(arr, arr.length - 1);
}
public static int[] ins(int[] a, int pos, int num) {
int[] result = new int[a.length];;
for(int i = 0; i < pos; i )
result[i] = a[i];
result[pos] = num;
for(int i = pos 1; i < a.length; i )
result[i] = a[i - 1];
return result;
}
public static void main(String[] args) {
int[] a = { 1, 2, 4 };
System.out.println(Arrays.toString(a));
a = add(a, 7);
System.out.println(Arrays.toString(a));
a = del(a);
System.out.println(Arrays.toString(a));
a = ins(a, 2, 3);
System.out.println(Arrays.toString(a));
}
}
Old Output
[1,2,4]
New Output
[1,2,3]
Desired Output
[1,2,3,4]
CodePudding user response:
You have two issues, first you need to increane the new array size by 1, note the 1 added here int[] result = new int[a.length 1];
. The second issue is that you need to use result.length
instead of a.length
on the last loop otherwise it uses the original shorter array length so the last value will never copy, the correct usage is for(int i = pos 1; i < result.length; i )
:
public static int[] ins(int[] a, int pos, int num) {
int[] result = new int[a.length 1];
for(int i = 0; i < pos; i )
result[i] = a[i];
result[pos] = num;
for(int i = pos 1; i < result.length; i )
result[i] = a[i - 1];
return result;
}
Now for the given input:
int[] a = { 1, 2, 4 };
a = ins(a, 2, 3);
System.out.println(Arrays.toString(a));
The output is as expected:
[1, 2, 3, 4]