简体   繁体   English

使用二维数组创建和打印乘法表?

[英]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. 我正在尝试使用二维数组创建12x12次表图表。 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. 这给出了一个12x12的表,但是没有进行乘法运算,该12x12点(网格中第12列第12行)是23而不是144,这现在让我认为实际的数组是错误的。 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 . String.format(...) ,考虑使用String.format(...)System.out.printf(...)来格式化输出,因为它比使用制表符\\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" 或者如果您希望输出权正确,请将"%6d"更改为"%-6d"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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