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

时间:2017-10-04 05:24:54

标签: java arrays

您好我正在尝试创建一个输出乘法网格的java程序,我想知道是否有办法在没有很多if语句的情况下执行它,如果我有n个值。这是代码

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;
        }

    }

}

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以定义表格大小并按如下方式打印乘法网格:

 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();
        }
      }