Java 2D阵列:乘法表

时间:2013-11-19 15:56:28

标签: java arrays multidimensional-array

我不确定为什么我的代码不起作用。请帮忙! :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;

3 个答案:

答案 0 :(得分:3)

Array的索引应该从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;
}

}

控制台输出:

 1  2  3  4  5 
 2  4  6  8 10 
 3  6  9 12 15 
 4  8 12 16 20 
 5 10 15 20 25 

答案 1 :(得分:1)

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();
}    

答案 2 :(得分:0)

如果您正在获取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;
}