Java 二维数组:乘法表

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

我不确定为什么我的代码不起作用。请帮助! :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;
java arrays multidimensional-array
4个回答
5
投票

数组的索引应该以

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
投票

如果你得到 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;
}

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

0
投票
public static int[][] productTable(int r, int c){
int [][] table = new int[r][c];
for (int row = 0; row < table.length ; row++)
{
  for (int column = 0; column < table[row].length; column++)
     {
        table[row][column] = (row)*(column);
      }

    }
    return table;
}
© www.soinside.com 2019 - 2024. All rights reserved.