【发布时间】:2019-07-03 14:22:39
【问题描述】:
我给出了一个二维数组(矩阵)和两个数字:i 和 j。我的目标是用矩阵中的索引 i 和 j 交换列。输入包含矩阵维度 n 和 m,不超过 100,然后是矩阵的元素,然后是索引 i 和 j。
我猜问题的根源与引用的变量有关?我试图用
替换第15行int nextValue = scanner.nextInt();
matrix[i][j] = nextValue;
swap[i][j] = nextValue;
但输出仍然保持不变......
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();
}
}
}
我的意见:
3 4
11 12 13 14
21 22 23 24
31 32 33 34
0 1
3 和 4 代表矩阵的行数和列数,以下三行定义矩阵的元素,最后一行告诉程序交换哪些列。
预期输出:
12 11 13 14
22 21 23 24
32 31 33 34
实际输出:
12 12 13 14
22 22 23 24
32 32 33 34
【问题讨论】:
标签: java