首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在java中复制二维数组的每隔一行和每隔一列。

在java中复制二维数组的每隔一行和每隔一列。
EN

Stack Overflow用户
提问于 2018-10-18 03:03:15
回答 1查看 179关注 0票数 0

我有一个二维int数组,需要使用java每隔一行和每隔一列复制一次(覆盖现有值,而不是创建新的列/行):

example

当前方法

     for(int i = 0; i < result.get(z).getWidth()-2; i+=1)
    {   for(int j = 0; j < result.get(z).getHeight()-2; j+=1)
    {   
        x[i+1][j] = result.get(z).getRGB(i, j);
        x[i][j+1] = result.get(z).getRGB(i, j);
        x[i+1][j+1] = result.get(z).getRGB(i, j);




    }

}
EN

回答 1

Stack Overflow用户

发布于 2018-10-18 06:08:01

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];
                }
            }
        }
    }

使用main函数进行测试:

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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52861916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档