Reputation: 47
I have an array of 4 int
s, and I need to replace them with values of another array. For example: I have an array {5,3,7,2}
, and I need to replace the values and get array {2,7,3,5}
.
Here's my code:
public static void main(String args[]){
int array[] = new int[4];
array[0] = 1;
array[1] = 4;
array[2] = 3;
array[3] = 7;
int swapArray[] = new int[5];
for (int j = 3; j > 0; j--) {
for (int i = 0; i < 4; i++) {
swapArray[j] = array[i];
System.out.print(" " + swapArray[j]);
}
}
}
But it doesn't change values, just repeats it 3 times.
Upvotes: 1
Views: 678
Reputation: 4418
If you want reverse an array :
With Commons.Lang, you could simply use
int array[] = new int[4];
array[0] = 1;
array[1] = 4;
array[2] = 3;
array[3] = 7;
ArrayUtils.reverse(array);
// For print output
System.out.println(Arrays.toString(array));
// Print output [7, 3, 4, 1]
Upvotes: 0
Reputation: 651
Maybe like this :
public static void main(String args[]){
int array[] = {1,4,3,7};
int swapArray[] = new int[array.length];
for(int i=0;i<array.length;i++)
swapArray[i]=array[array.length-1];
System.out.print(" " + swapArray[i]);
}
}
Upvotes: 3
Reputation: 201537
It appears that you want to reverse the array. You could do it in place like,
int[] arr = { 5, 3, 7, 2 };
System.out.println(Arrays.toString(arr));
for (int i = 0; i < arr.length / 2; i++) {
int t = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = t;
}
System.out.println(Arrays.toString(arr));
Or, you could copy it to a new (reversed) array like,
int[] arr = { 5, 3, 7, 2 };
System.out.println(Arrays.toString(arr));
int[] arr2 = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
arr2[arr2.length - i - 1] = arr[i];
}
System.out.println(Arrays.toString(arr2));
Both examples output (the requested)
[5, 3, 7, 2]
[2, 7, 3, 5]
Upvotes: 2