user2990722 user2990722 - 2 months ago 11
Java Question

Java 2D Array: Multiplication Table

I'm not sure why my code will not work. Help please! :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;

Answer

The index of Array should start 0 rather 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 
Comments