I have an Array:
int[] arr = {-15, -23, -34, -22, 2};
I am trying to do an if statement, if values are below 0, then the array value changes to -1. If the values are above 0 the array values are changed to 1.
public static void main(String[] args) {
int[] swap;
int[] arr = {-15, -23, -34, -22, 2};
swap = arr;
for (int x = 0; x < arr.length; x++) {
System.out.println(arr[x]+swap[x]);
}
for (int i = 0; i < arr.length; i++) {
// System.out.println(arr[i]);
if (arr[i] < 0) {
arr[i] = -1;
System.out.println("Oringinal value "+swap[i] + " Error Code: " + arr[i]);
}
if (arr[i] > 0) {
arr[i] = 1;
System.out.println("Oringinal value "+swap[i] + " Error Code: " + arr[i]);
}
}
}
My current code is above.
The objective is to print the original array value with the changed "error code".
However the print out is retuning the same value with the original value.
Oringinal value -1 Error Code: -1
Oringinal value -1 Error Code: -1
Oringinal value -1 Error Code: -1
Oringinal value -1 Error Code: -1
Oringinal value 1 Error Code: 1
What am I doing wrong?
swap-Array.int[] swap = Arrays.copyOf(arr, arr.length);swapis, but you see the new value ofarr[i]simply because you set it prior to printing it.swap=arrdoes not make a copy of the elements of the array, this wayarrandswapare two names for a single array.