简体   繁体   中英

Creating and printing a multiplication table using a two dimensional arrays?

I'm trying to create a 12x12 times table chart using a two dimensional array. I tried the below code to actually create the array:

    int[][] table = new int[12][12];

    for (int row=0; row<12; row++){
      for (int col=0; col<12; col++){
        table[row][col] = row+1 * col+1;

      }
    }

Now I can't quite figure out how to display it properly, I tried this:

for(int row=0; row<table.length; row++) {
  for(int col=0; col<table[row].length; col++)
    System.out.print(table[row][col] + "\t");
  System.out.println();
}

This gives a 12x12 table but there is no multiplication going on, the 12x12 spot (12th col 12th row in grid) is 23 instead of 144, which now makes me think the actual array is wrong. Any ideas?

Use parentheses in your math statement. Know that multiplication has precedence over addition.

So your line of code:

table[row][col] = row+1 * col+1;

is equivalent to

table[row][col] = row + (1 * col) + 1;

Which is not what you want. You want:

table[row][col] = (row + 1) * (col + 1);

As an aside, consider using String.format(...) or System.out.printf(...) for formatting your output since it is much more powerful and flexible than using tabs, \\t . Also, at your stage in the game, you should enclose all if blocks and all loops inside of {...} curly braces as this will save your tail at a later date.

eg,

  for (int row = 0; row < table.length; row++) {
     for (int col = 0; col < table[row].length; col++) {
        System.out.printf("%6d", table[row][col]);
     }
     System.out.println();
  }

or if you want the output right justified, change "%6d" to "%-6d"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM