Java 2D 数组:乘法表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20076142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:54:42  来源:igfitidea点击:

Java 2D Array: Multiplication Table

javaarraysmultidimensional-array

提问by user2990722

I'm not sure why my code will not work. Help please! :D

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

采纳答案by MouseLearnJava

The index of Array should start 0rather 1.

数组的索引应该开始0相当1

Change to the following code and have a try.

改成下面的代码试试看。

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

Test code and output in console is as follows:

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

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

}

Output in Console:

控制台输出:

 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 

回答by Harry

If you're getting ArrayIndexOutOfBounds its because you are starting from index 1, when it should be 0.

如果你得到 ArrayIndexOutOfBounds 是因为你是从索引 1 开始的,它应该是 0。

This should do the job:

这应该可以完成这项工作:

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

回答by Anurag Suman

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