当我输入一个数字时,将打印一个表格,如下图所示。 Expected output
我不知道如何调整" - "根据输出的长度打印。 我还尝试使用不同的数学计算,使用整数变量来增加字符数量并打印相同数量的" - "。
这是我的输出: Output
这是我的代码:
Scanner keyboard = new Scanner(System.in);
int num;
char line = 45;
StringBuilder sb = new StringBuilder();
do {
System.out.println("Enter a number between 1 and 30");
num = keyboard.nextInt();
if (num == 0) System.exit(0);
} while (num < 1 || num > 30);
//TOP LINES --> THIS IS THE PROBLEM
for (int i = 0; i < num; i++) {
for (int j = 0; j < num/4; j++) {
sb.append(line);
}
}
System.out.println(sb);
//PRINTS FIRST PIPE
System.out.printf("|");
for (int n = 1; n <= num*num; n++) {
System.out.printf(" %-3d|", n);
if (n % num == 0 && n != num*num){
System.out.println();
System.out.printf("|");
}
}
//BOTTOM LINES
System.out.println("\n" + sb);
答案 0 :(得分:0)
更改循环以计算&#39; - &#39; s
的数量//TOP LINES --> THIS IS THE PROBLEM
for (int i = 0; i < num; i++) {
for (int j = 0; j < num/4; j++) {
sb.append(line);
}
}
System.out.println(sb);
>>>>>>> TO <<<<<<<<
//Determine the column size
String largestValue = "" + (num * num); // for 20, this is "400"
int strLen = largestValue.length(); // for 20, this is 3 + 1 space+ for right '|'
int width = (num * (strLen + 2));
width++; // for right '|'
//TOP LINES
for (int i = 0; i < width; i++) {
System.out.print('_'); // I'm outputting an underscore
}
System.out.println("");
System.out.print("|");
for (int n = 1; n <= num; n++) {
System.out.printf(" %-" + strLen + "d|", n);
}
System.out.println("");
for (int row = 1; row <= num; row++) {
System.out.print("|");
for (int column = 1; column <= num; column++) {
System.out.printf(" %-" + strLen + "d|", (row * column));
}
System.out.println("");
}
//bottom LINES
for (int i = 0; i < width; i++) {
System.out.print('_');
}
System.out.println("");