用Java 写一个乘法表如图所示,要求part one 使用一个while循环 part two 使用for嵌套循环
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5....
6 ....
7 ....
8 ....
9 ...
我已经写了一个不过那上下对不齐。。。
各位帮我看看是哪出错了。。。。
public class MultiTest{
public static void main(String[] args){
int i = 1,j = 1;
System.out.print(" MultiTest Table "+"\n");
System.out.print("---------------------"+"\n");
System.out.print(" ");
while(i <= 9)
{
System.out.print(i + " ");
//i++;
for(i = 1;i < 9;i++)
{
System.out.println(i);
for(j = 1;j <= 9;j++)
{
System.out.print(i * j + " ");
}
}
i++;
}
//System.out.println();
/*for(i = 1;i <= 9;i++)
{
System.out.println(i);
for(j = 1;j <= 9;j++)
{
System.out.print(i * j + " ");
}
}*/
}
}
------解决方案--------------------------------------------------------
九九乘法表还是很好控制格式的,因为输出的数只有一位整数和两位整数两种情况,作个简单的判断就行了:
- Java code
public class MultiTest { public static void main(String[] args) { System.out.println(" MultiTest Table "); System.out.println("---------------------"); showTable1(); } static void showTable1() { System.out.print(" "); for (int i = 1; i < 10; i++) System.out.print(i + " "); System.out.println(); for (int i = 1; i < 10; i++) { System.out.print(i + " "); for (int j = 1; j < 10; j++) System.out.print(i * j + (i * j > 9 ? " " : " ")); System.out.println(); } }}
------解决方案--------------------------------------------------------
PS:对于格式化输出效果,用格式化输出函数System.out.printf(System.out.format)要比System.out.print容易得多:
- Java code
public class MultiTest { public static void main(String[] args) { System.out.println(" MultiTest Table "); System.out.println("---------------------"); // showTable1(); showTable2(); } static void showTable1() { System.out.print(" "); for (int i = 1; i < 10; i++) System.out.print(i + " "); System.out.println(); for (int i = 1; i < 10; i++) { System.out.print(i + " "); for (int j = 1; j < 10; j++) System.out.print(i * j + (i * j > 9 ? " " : " ")); System.out.println(); } } static void showTable2() { System.out.print(" "); for (int i = 1; i < 10; i++) System.out.printf("%-3d", i); System.out.println(); for (int i = 1; i < 10; i++) { System.out.printf("%-2d", i); for (int j = 1; j < 10; j++) System.out.printf("%-3d", i * j); System.out.println(); } }}