I have given a two-dimensional array (matrix) and the two numbers: i and j. My goal is to swap the columns with indices i and j within the matrix. Input contains matrix dimensions n and m, not exceeding 100, then the elements of the matrix, then the indices i and j.
I guess the origin of the problem has something to do with referenced variables? I tried to replace line 15 with
int nextValue = scanner.nextInt();
matrix[i][j] = nextValue;
swap[i][j] = nextValue;
but still the output remains the same...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int column = scanner.nextInt();
int[][] matrix = new int[row][column];
int[][] swap = matrix.clone();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
matrix[i][j] = scanner.nextInt();
}
}
int c0 = scanner.nextInt();
int c1 = scanner.nextInt();
for (int i = 0; i < row; i++) {
swap[i][c0] = matrix[i][c1];
swap[i][c1] = matrix[i][c0];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(swap[i][j] + " ");
}
System.out.println();
}
}
}
My Input:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
0 1
3 and 4 stands for the number of rows and columns of the matrix, the following three lines define the elements of the matrix and the last line tells the program which columns so swap.
Expected Output:
12 11 13 14
22 21 23 24
32 31 33 34
Actual Output:
12 12 13 14
22 22 23 24
32 32 33 34