需求列印 1~199 公斤對應磅數(1 公斤 = 2.2 磅),程式碼如下:
public class WeightTable {
public static void main(String[] args) {
System.out.printf("%-5s %-5s%n", "KG", "POUND");
for (int i = 1; i <= 199; i++) {
System.out.printf("%-5d %-5.1f%n", i, i * 2.2);
}
}
}使用 printf 格式化輸出,%-5d 左對齊寬度 5,%-5.1f 保留一位小數。此為基礎迴圈練習,適合初學者理解格式化輸出與型別轉換。