简体   繁体   English

创建乘法表的最佳方法-java

[英]Optimal way to creating a multiplication table -java

Hello I am trying to create a java program that output multiplication grid and I want to know if there is way to do it without having a lot of if statement if I had n values.您好,我正在尝试创建一个输出乘法网格的 Java 程序,如果我有 n 个值,我想知道是否有办法在没有大量 if 语句的情况下做到这一点。 Here is the code这是代码

public class MultiplicationGrid {

public static void main(String[] args) {

    int num[][] = new int[4][4];

    //String size[][] = new String[1][13];
    for(int i = 0; i < num.length; ++i) {
        for(int j = 0; j < num[i].length;++j) {
            num[i][j] = (j+1)*(i+1);
        }   
    }

    int count = 0;
    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    for (int i = 0; i < num.length; ++i)    {
        for(int j = 0; j < num[i].length; ++j) {
        if(count == 0) {
            count = num [i][j];
            continue;
        }
        if(count1 == 0) {
            count1 = num [i][j];
            continue;
        }
        if(count2 == 0) {
            count2 = num [i][j];
            continue;
        }
        if(count3 == 0) {
            count3 = num [i][j];

        }
        System.out.println(count + "    " + (count1) + "    " + (count2) + "    " + (count3));
        count = 0;
        count1 = 0;
        count2 = 0;
        count3 = 0;
        }

    }

}

} }

Thanks in advance.提前致谢。

You can define the table size and print the multiplication grid as follows:您可以定义表格大小并打印乘法网格,如下所示:

 public static void main(String[]args) {
        final int TABLE_SIZE = 12;
        // Declare the rectangular array to store the multiplication table:
        int[][] table = new int[TABLE_SIZE][TABLE_SIZE];

        // Fill in the array with the multiplication table:
        for(int i = 0 ; i < table.length ; ++i) {
          for(int j = 0 ; j < table[i].length ; ++j) {
            table[i][j] = (i+1)*(j+1);
          }
        }

        // Output the table heading
        System.out.print("      :");             // Row name column heading
        for(int j = 1 ; j <= table[0].length ; ++j) {
          System.out.print((j<10 ? "   ": "  ") + j);
        }
        System.out.println("\n-------------------------------------------------------");

        // Output the table contents          
        for(int i = 0 ; i < table.length ; ++i) {
          System.out.print("Row" + (i<9 ? "  ":" ") + (i+1) + ":");

          for(int j = 0; j < table[i].length; ++j) {
            System.out.print((table[i][j] < 10 ? "   " : table[i][j] < 100 ? "  " : " ") + table[i][j]);
          }
          System.out.println();
        }
      }

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

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