如何修改乘法表首列打印变量的值,实现x、1-10显示
解决Java乘法表首列显示问题:替换0为x、1-10
别担心,刚接触Java和Stack Overflow完全没问题,咱们一起把这个乘法表的小问题解决掉~
首先我猜你可能写了类似这样的初始代码(这是新手写乘法表时很常见的写法):
public class MultiplicationTable { public static void main(String[] args) { for (int i = 0; i <= 10; i++) { for (int j = 0; j <= 10; j++) { if (j == 0) { System.out.print(i + "\t"); } else { System.out.print(i * j + "\t"); } } System.out.println(); } } }
这段代码的问题在于外层循环从0开始,所以首列第一个输出是0,后面跟着0-10,不符合你要的x、1、2...10的需求。咱们可以通过两种方式修改:
方式一:拆分表头和内容行(更清晰直观)
这种写法把表头(第一行)和后面的内容行分开处理,逻辑更易懂:
public class MultiplicationTable { public static void main(String[] args) { // 先打印表头:左上角的x,再打印1-10作为列标题 System.out.print("x\t"); for (int j = 1; j <= 10; j++) { System.out.print(j + "\t"); } System.out.println(); // 换行到下一行 // 打印10行内容,首列显示1-10 for (int i = 1; i <= 10; i++) { // 先打印当前行的首列数字(1到10) System.out.print(i + "\t"); // 打印该行的乘法结果 for (int j = 1; j <= 10; j++) { System.out.print(i * j + "\t"); } System.out.println(); // 换行 } } }
逻辑说明:
- 单独处理第一行:先输出
x作为左上角标识,再循环打印1-10作为列的标题 - 外层循环从
1开始到10,每一行开头先打印当前的行号(也就是首列的1-10),然后内层循环计算并打印该行的乘积
方式二:用条件判断处理特殊位置(适合保留原有循环结构)
如果你不想拆分循环,也可以在原有双层循环里加条件判断,区分左上角、首列、表头和普通内容:
public class MultiplicationTable { public static void main(String[] args) { for (int i = 0; i <= 10; i++) { for (int j = 0; j <= 10; j++) { if (i == 0 && j == 0) { // 左上角特殊位置,输出x System.out.print("x\t"); } else if (j == 0) { // 首列非左上角,输出当前行号i(i从1到10) System.out.print(i + "\t"); } else if (i == 0) { // 第一行非左上角,输出当前列号j(j从1到10) System.out.print(j + "\t"); } else { // 普通位置,输出乘积 System.out.print(i * j + "\t"); } } System.out.println(); } } }
逻辑说明:
通过判断i和j的数值,分别处理四个场景:左上角的x、首列的行号、第一行的列号、其他位置的乘积,这样也能完美实现你要的效果。
不管选哪种方式,运行后首列都会显示x、1、2...10,乘法表的内容也完全正确啦~
内容的提问来源于stack exchange,提问作者Sam Herman
相关产品推荐
相关产品推荐

