Java二维数组:乘法表

pu82cl6c  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(110)

我不知道为什么我的代码无法工作。请帮助!:D

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[r][c];
    for (int row = 1; row <= yes.length ; row++)
    {
        for (int column = 1; column <= yes[row].length; column++)
        {
            yes[row][column] = (row)*(column);
        }

    }
    return yes;
ckocjqey

ckocjqey1#

数组的索引应从0开始,而不是从1开始。
更改为以下代码并尝试一下。

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[r][c];
    for (int row = 0; row < yes.length ; row++)
    {
        for (int column = 0; column < yes[row].length; column++)
        {
             yes[row][column] = (row+1)*(column+1);         }

    }
    return yes;
}

控制台中的测试代码和输出如下:

public class Test1 {

public static void main(String[] args) {

    int[][] data = new int[5][5];

    data = timesTable(5,5);

    for (int row = 0; row < data.length ; row++)
    {
        for (int column = 0; column < data[row].length; column++)
        {
            System.out.printf("%2d ",data[row][column]);
        }
        System.out.println();

    }
}

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[r][c];
    for (int row = 0; row < yes.length ; row++)
    {
        for (int column = 0; column < yes[row].length; column++)
        {
            yes[row][column] = (row+1)*(column+1);
        }

    }
    return yes;
}

}

控制台中的输出:

uttx8gqw

uttx8gqw2#

如果你得到了ArrayIndexOutOfBounds,那是因为你从索引1开始,而它应该是0。
这应该可以完成任务:

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[r][c];
    for (int row = 1; row <= yes.length ; row++)
    {
      for (int column = 1; column <= yes[row].length; column++)
      {
        yes[row-1][column-1] = (row)*(column);
      }

    }
    return yes;
}
t98cgbkg

t98cgbkg3#

int a[][]={{2,3},{3,4}};
int b[][]={{2,3},{3,4}};
int c[][]=new int[2][2];
 for(int i=0;i<2;i++){
 for(int j=0;j<2;j++){
   c[i][j]=a[i][j]*b[i][j];
   System.out.print(c[i][j]+"\t"); 
 }   
 System.out.println();
}

相关问题