harold_finch harold_finch - 2 months ago 10
Java Question

Multiplying table by using two dimensional arrays

I am trying to make a multiplication table from 1 to 10 by using two dimensional arrays. When I run the program I get each value under each other, not a table. I get the first value as 1 and all others 0. I also get the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at summing.main(summing.java:46)
Could you give some tips about the algorithm?

public static void main( String[] args)
{
Scanner scan = new Scanner( System.in);
int x,y,z;
int[][] table = new int[11][11];
table[0][0] = 0;
table[0][1] = 1;
table[0][2] = 2;
table[0][3] = 3;
table[0][4] = 4;
table[0][5] = 5;
table[0][6] = 6;
table[0][7] = 7;
table[0][8] = 8;
table[0][9] = 9;;
table[0][10] = 10;
table[1][0] = 1;
table[2][0] = 2;
table[3][0] = 3;
table[4][0] = 4;
table[5][0] = 5;
table[6][0] = 6;
table[7][0] = 7;
table[8][0] = 8;
table[9][0] = 9;
table[10][0] = 10;

System.out.println( "Start of multiplication\n");

for (x = 0; x <= 10; x++)
{
for (y = 0; y <= 10; y++)
{
table[x][y] = table[x][1] * table[y][1];
System.out.println(table[x][y]);//This line has the error.
}
table[x][y] = table[x][1] * table[y][1];
System.out.print(table[x][y]);
}

System.out.println( "\nEnd of multiplication\n" );
}

Answer

You can try this, if you cannot get the error in your code. But first try to find the solution using your code as @T.J. Crowder said:

public static void main( String[] args) 
{
   // Scanner scan = new Scanner( System.in);
    int x,y;
    int[][] table = new int[11][11];
    table[0][0] = 0;
    table[0][1] = 1;
    table[0][2] = 2;
    table[0][3] = 3;
    table[0][4] = 4;
    table[0][5] = 5;
    table[0][6] = 6;
    table[0][7] = 7;
    table[0][8] = 8;
    table[0][9] = 9;;
    table[0][10] = 10;  
    table[1][0] = 1;
    table[2][0] = 2;
    table[3][0] = 3;
    table[4][0] = 4;
    table[5][0] = 5;
    table[6][0] = 6;
    table[7][0] = 7;
    table[8][0] = 8;    
    table[9][0] = 9;
    table[10][0] = 10;

    int[][] output_table = new int[11][11];

    System.out.println( "Start of multiplication\n");

    for (x = 0; x < 10; x++)
    {
        System.out.println("Table of: "+table[x][0]);
        for (y = 0; y < 10; y++)
        {
            output_table[x][y] = table[0][x] * table[y][0];
            System.out.print(output_table[x][y]+"\t");//This line has the error.
        }

        output_table[x][y] = table[0][x] * table[y][0];
        System.out.println(output_table[x][y]);  
    }

    System.out.println( "\nEnd of multiplication\n" );
}

`

Comments