如何将数组的值添加到一个矩阵的列?

问题描述 投票:0回答:3

我在Java中做一些示例尝试将数组的值添加到矩阵的列中。但问题是我不知道为什么矩阵没有改变:

例如:输入:

array  = 1 1 1 1 

matrix = 0 0 0 0
         0 0 0 0
         0 0 0 0
         0 0 0 0

输出应该是:

1 0 0 0
1 0 0 0
1 0 0 0 
1 0 0 0

这是我的代码:

 public static void main(String[] args)
{
    int col = 0, row = 0;
    int [][]a = new int[4][4];
    int[]temp = new int[4];
    for( row = 0 ; row<4;row++)
    {
        for( col = 0 ; col<4 ;col++)
        {
            a[row][col] = 0;
        }
    }
    for(row = 0; row<4;row++)
    {
        temp[row] = 1;
    }

    while(col<4)
    {
        for(row = 0; row <4; row++)
        {
            a[row][col] = temp[row];

        }
        row+=1;
    }
    for( row = 0 ; row<4;row++)
    {
        System.out.print(temp[row] + " ");
    }
    System.out.println();
    for( row = 0 ; row<4;row++)
    {
        for( col = 0 ; col<4 ;col++)
        {
            System.out.print(a[row][col]+ "   ");
        }
        System.out.println();
    }


}

目前,矩阵仍为零。有没有其他方法可以解决这个问题?

java
3个回答
0
投票

你需要改变

 while(col<4)
{
    for(row = 0; row <4; row++)
    {
        a[row][col] = temp[row];

    }
    row+=1;
}

    col = 0;

    for (row = 0; row < 4; row++) {
        a[row][col] = temp[row];
    }

0
投票

请注意,这里:

   while(col<4)
    {
        for(row = 0; row <4; row++)
        {
            a[row][col] = temp[row];

        }
        row+=1;
    }

你正在添加行+ = 1,但循环是关于cols。这可能是意外行为的原因之一。

同时,当您使用之前使用的相同迭代器时 - 永远不会执行此循环。 (col已经从第一循环开始== 4)


0
投票

我假设您将知道您必须用数组中指定的值替换哪一列(在您的情况下,它是第1列)

无论如何,你的while循环中的值是不正确的,因为你已经使用了相同的局部变量col,它已经是你之前的for循环中的4,所以你的while循环永远不会执行。将其替换为变量值的一些变化,如此 -

       int foo = 0;  //initialize a new variable for the loop cycles
       col = 0;      // set the value of col to the column you want to replace
       while (foo < 4)
        {
            for(row = 0; row <4; row++)
            {
                a[row][col] = temp[row];

            }
            row+=1;
            foo++;
        }

应该解决它。

© www.soinside.com 2019 - 2024. All rights reserved.