0
以下程序打印乘法表9xN,其中N由用戶給出。只有當產品長度爲2個數字時,我的電池纔會固定以便對齊。如何動態格式化Java中的字符串
我該怎麼做才能讓單元格與任何大小的數字對齊?
public static void main(String[] args) {
//Reading the number n.
System.out.print("Give a number: ");
int n = StdIn.readInt();
//Validating the number.
while(n<1) {
System.out.println("Please give a number greater or equal to 1");
n = StdIn.readInt();
}
/*---------------------------------
*
*Lines 27-36 -> Creating the first
*line and the first line's design.
*
----------------------------------*/
for (int i = 1; i <= n; i++) {
System.out.printf(" %-4d", i);
}
System.out.println();
System.out.print(" +");
for (int i = 1; i <= n; i++) {
System.out.print("-------+");
}
System.out.println();
/*----------------------------------
*
*Lines 45-58 -> Printing the product
*of the numbers and the design of
*the table.
*
----------------------------------*/
for (int i = 1; i <=9 ; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= n; j++) {
int a = (i * j);
String b = " | ";
System.out.printf("%2d %s", a, b);
}
System.out.println();
System.out.print(" +");
for (int k = 1; k <= n; k++) {
System.out.print("-------+");
}
System.out.println();
}
}
}
我該怎麼做,所以細胞將與任何大小的數字對齊?
在此先感謝。
計算的最大數量,並使用長度 –
我認爲[這](https://開頭dzone.com/articles/java-string-format-examples)會幫助你 –