0
public static void main (String [] args)
{       
    int q, r, s, t, u, v, w, x, y, z;

    for (q=1; q<=10; q++)
    { 
        System.out.print("\t" + q);
    }
    System.out.println();
    for (r=2; r<=20; r += 2)
    {
        System.out.print("\t" + r);
    }
    System.out.println();
    for (s=3; s<=30; s += 3)
    {
        System.out.print("\t" + s);
    }
    System.out.println();
    for (t=4; t<=40; t += 4)
    {
        System.out.print("\t" + t);
    }
    System.out.println();
    for (u=5; u<=50; u += 5)
    {
        System.out.print("\t" + u);
    }
    System.out.println();
    for (v=6; v<=60; v += 6)
    {
        System.out.print("\t" + v);
    }
    System.out.println();
    for (w=7; w<=70; w += 7)
    {
        System.out.print("\t" + w);
    }
    System.out.println();
    for (x=8; x<=80; x += 8)
    {
        System.out.print("\t" + x);
    }
    System.out.println();
    for (y=9; y<=90; y += 9)
    {
        System.out.print("\t" + y);
    }
    System.out.println();
    for (z=10; z<=100; z += 10)
    {
        System.out.print("\t" + z);
    }

}

尽管这个程序看起来很荒谬,但它以所需的格式显示了一个乘法表。作为一个菜鸟(如您所见)并尝试学习这些嵌套循环非常令人困惑,尤其是当教程说这个乘法表采用相同的确切格式时,可以只使用嵌套的 for 循环和 System.out 来编写。印刷厂 本教程没有一点帮助,并且给出了嵌套 for 循环的相当简单的用法,现在我看不出它如何适用于简化这个程序......但它说它可以做到,所以它可以做到。

4

4 回答 4

2

这是您将在任何初学者书籍中学到的内容:

for (int i=1;i<=10;i++){
  for (int j=1;j<=10;j++)
     System.out.print("\t"+i*j);
  System.out.println(); 
}
于 2012-10-26T20:42:35.490 回答
0

这可以使用数组按预期工作

public static void main(String[] args) {
int[][] array = new int[11][11];
for (int i=1; i<array.length; i++) {
for (int j=1; j<array[i].length; j++) {
array[i][j] = i*j;
System.out.print(" " + array[i][j]);
}
System.out.println("");
}
}
于 2012-10-26T20:40:41.453 回答
0

你的意思是这样的: -

   for (int i = 1; i <= 10; i++) {
        for (int j = i; j <= 10 * i; j += i) {
            System.out.print(j + " ");
        }
        System.out.println();
   }
于 2012-10-26T20:41:40.510 回答
0

这是我对漂亮打印的看法(单个单元格右/左对齐):

private static void printMultiplicationTable(int m, int n) {
    int[][] arr = new int[m][n];
    int[] maxes = new int[n];

    for (int i = 1; i <= m; i++) {
        for (int j = i, k = 1; j <= n * i; j += i) {
            arr[i-1][k-1] = j;
            if ((maxes[k-1]+"").length() < (j+"").length()) {
                maxes[k-1] = (j+"").length();
            }
            k++;
        }
   }

    for(int i=0; i<arr.length; i++) {
        for(int j=0; j<arr[i].length; j++)
            System.out.print(adjust(arr[i][j], maxes[j], true) + " ");
        System.out.println();
    }
}

private static String adjust(int n, int tot, boolean rightJustify) {
    StringBuffer buff = new StringBuffer();

    for(int i=1; i<=tot - (n + "").length(); i++) {
        buff.append(" ");
    }

    if (rightJustify) {
        buff.append(n);
        return buff.toString();
    } else {
        return n + buff.toString();
    }
}
于 2012-10-26T21:33:08.260 回答