I have created one method called rowSwitching to switch data on two specific row in array. However, when i used it the array value at the main also changed even though i don't want to store it.
Here's my code ;
public class MatrixEx {//implements Matrix {
public static void print(int[][] input1, int[][] input2) {
System.out.println("------------------ ------------------");
for (int row = 0; row < input1.length; row++) {
for (int col = 0; col < input1.length; col++) {
System.out.format("%4d", input1[row][col]);
}
System.out.print(" ");
for (int col = 0; col < input2.length; col++) {
System.out.format("%4d", input2[row][col]);
}
System.out.println();
}
System.out.println("------------------ ------------------");
}
public static void main(String[] args) {
int[][] input1 = {
{7, 2, 1},
{0, 3, -1},
{-3, 4, -2}
};
int[][] input2 = {
{-2, 8, -5},
{3, -11, 7},
{9, -34, 21}
};
System.out.format("%12s%4s%12s\n", "input1", " ", "input2");
print(input1, input2);
MatrixEx matrixFunc = new MatrixEx();
print(input1, matrixFunc.rowSwitching(input1, 1, 2));
}
public int[][] rowSwitching(int[][] matrix, int row1, int row2) {
System.out.format("%12s%4s%12s\n", "Before", " ", "After");
int[] temp1 = new int[matrix.length];
int[] temp2 = new int[matrix.length];
int[][] result = matrix;
row1 -= 1;
row2 -= 1;
for (int i = 0; i < temp1.length; i++) {
temp1[i] = result[row1][i];
}
for (int i = 0; i < temp2.length; i++) {
temp2[i] = result[row2][i];
}
for (int i = 0; i < result.length; i++) {
result[row1][i] = temp2[i];
}
for (int i = 0; i < result.length; i++) {
result[row2][i] = temp1[i];
}
return result;
}
I want to keep the array value at the main, but for some reason it keeps changing after i use the method.