gpt4 book ai didi

java - 用行间距格式化乘法表

转载 作者:行者123 更新时间:2023-11-30 02:31:55 24 4
gpt4 key购买 nike

我正在尝试制作一个与用户指定的一样大的乘法表。我遇到的问题是格式。现在的输出将所有数字打印到一行,而我希望将其全部打印在一张漂亮整洁的表格上的多行上。按照原样格式化,我无法判断 \n 将去哪里执行此操作,或者是否有其他方法。

这是我的代码:

import java.util.*;

public class question2 {

public static void main(String [] args) {

Scanner keyb = new Scanner(System.in);

int i = 0;

while (i<=0 || i>=11) {
System.out.print("please enter an integer between 1 and 10: ");
i = keyb.nextInt();
}

for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
}
}
}

编辑:整数 5 的输出如下所示:

1 1 2 3 4 5 2 2 4 6 8 10 3 3 6 9 12 15 4 4 8 12 16 20 5 5 10 15 20 25

最佳答案

在第二个 for 循环之后,添加新行 \n:

for (int x = 1; x <= i; x++) {
System.out.printf("%4d",x);
for (int y = 1; y <= i; y++){
System.out.printf("%4d",x*y);
}
System.out.println();
}

关于java - 用行间距格式化乘法表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44091610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com