2 回答
TA贡献1963条经验 获得超6个赞
if/else 的另一种方法:
private static void duplicateAlternatesWithIfElse(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix.length; col++) {
if ((row - 1) % 2 == 0) {
matrix[row][col] = matrix[row - 1][col];
} else if ((col - 1) % 2 == 0) {
matrix[row][col] = matrix[row][col - 1];
}
}
}
}
使用主函数测试:
public static void main(String[] args) {
int[][] twoDimArray = {
{ 10, 17, 200, 255, 0 },
{ 0, 199, 100, 30, 45 },
{ 250, 23, 177, 180, 79 },
{ 0, 9, 14, 150, 70 },
{ 50, 55, 187, 10, 233 }
};
printMatrix(twoDimArray);
duplicateAlternatesWithIfElse(twoDimArray);
printMatrix(twoDimArray);
}
输出:
10 17 200 255 0
0 199 100 30 45
250 23 177 180 79
0 9 14 150 70
50 55 187 10 233
10 10 200 200 0
10 10 200 200 0
250 250 177 177 79
250 250 177 177 79
50 50 187 187 233
TA贡献1817条经验 获得超14个赞
替代方法:
private static void duplicateAlternates(int[][] matrix) {
for (int row = 0; row < matrix.length; row += 2)
for (int col = 1; col < matrix.length; col += 2)
matrix[row][col] = matrix[row][col - 1];
for (int row = 1; row < matrix.length; row += 2)
for (int col = 0; col < matrix.length; col++)
matrix[row][col] = matrix[row - 1][col];
}
测试
public static void main(String[] args) {
int[][] matrix = { { 10, 17, 200, 255, 0 },
{ 0, 199, 100, 30, 45 },
{ 250, 23, 177, 180, 79 },
{ 0, 9, 14, 150, 70 },
{ 50, 55, 187, 10, 233 } };
print(matrix);
duplicateAlternates(matrix);
print(matrix);
}
private static void print(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.printf(" %3d", matrix[row][col]);
System.out.println();
}
System.out.println();
}
输出
10 17 200 255 0
0 199 100 30 45
250 23 177 180 79
0 9 14 150 70
50 55 187 10 233
10 10 200 200 0
10 10 200 200 0
250 250 177 177 79
250 250 177 177 79
50 50 187 187 233
添加回答
举报