一一得一 一二得二 一三得三 ... 一九得九
二二得四 二三得六 ... 二九一十八
...
九九八十一
public class ChineseNumber {
private static final String[] DIGITS = {"零","一","二","三","四","五","六","七","八","九"};
private static final String[] UNITS = {"","十","百","千"};
public static String toChinese(int num) {
if (num == 0) return DIGITS[0];
StringBuilder sb = new StringBuilder();
int unit = 0;
while (num > 0) {
int digit = num % 10;
if (digit != 0) {
sb.insert(0, DIGITS[digit] + UNITS[unit]);
} else if (sb.length() > 0 && sb.charAt(0) != DIGITS[0].charAt(0)) {
sb.insert(0, DIGITS[0]); // 中間的零
}
num /= 10;
unit++;
}
// 特殊處理:10-19 的 "一十" 簡寫為 "十"
if (sb.length() == 2 && sb.charAt(0) == '一' && sb.charAt(1) == '十') {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
public static void printTableClassic() {
for (int i = 1; i <= 9; i++) {
for (int j = i; j <= 9; j++) {
String mul = toChinese(i * j);
System.out.print(toChinese(i) + toChinese(j) + (i*j >= 10 ? "" : "得") + mul + " ");
}
System.out.println();
}
}
public static void printTableStream() {
IntStream.rangeClosed(1, 9).forEach(i -> {
IntStream.rangeClosed(i, 9)
.mapToObj(j -> toChinese(i) + toChinese(j) + (i*j >= 10 ? "" : "得") + toChinese(i*j))
.forEach(s -> System.out.print(s + " "));
System.out.println();
});
}
public static void printTableRecursive(int row, int col) {
if (row > 9) return;
if (col > 9) { System.out.println(); printTableRecursive(row+1, row+1); return; }
System.out.print(toChinese(row) + toChinese(col) + (row*col>=10?"":"得") + toChinese(row*col) + " ");
printTableRecursive(row, col+1);
}
// 調用: printTableRecursive(1, 1);
public static void printTableAligned() {
// 計算最大寬度 (如 "九九八十一" 6字符)
int maxW = Arrays.stream(new int[]{9*9}).map(ChineseNumber::toChinese).mapToInt(String::length).max().orElse(6);
for (int i=1; i<=9; i++) {
for (int j=i; j<=9; j++) {
String cell = toChinese(i)+toChinese(j)+(i*j>=10?"":"得")+toChinese(i*j);
System.out.printf("%-" + (maxW+1) + "s", cell);
}
System.out.println();
}
}
public class MultiplicationTableCN {
public static void main(String[] args) {
System.out.println("=== 經典雙層循環 ===");
printTableClassic();
System.out.println("\n=== Stream 風格 ===");
printTableStream();
System.out.println("\n=== 遞歸實現 ===");
printTableRecursive(1, 1);
System.out.println("\n=== 對齊輸出 ===");
printTableAligned();
}
// 這裡放入上述所有輔助方法...
}
NumberFormatter 接口,支持英文、日文、羅馬數字等九九乘法表是經典練習題,通過中文轉換邏輯的封裝,展示了字符串構建、流式編程、遞歸思維、格式化輸出等多種 Java 技術點。實際項目中,將數字格式化邏輯抽離為獨立工具類,配合完善測試,是更專業的做法。