// 1. 聲明並初始化 int amount = 100; int price = 0; // 2. 後續賦值(覆蓋原值) price = 23; // 直接賦值 amount = 200; // 重新賦值 // 3. 表達式賦值 int change = amount - price; // 運算結果賦值 // 4. 連續賦值 int a = 1, b = 2, c = 3; int x = y = z = 10; // 右結合:z=10 → y=10 → x=10
Scanner in = new Scanner(System.in);
System.out.print("請輸入票面金額:"); // print 不換行,光標停留行尾
int amount = in.nextInt();
System.out.print("請輸入購買金額:");
int price = in.nextInt();
System.out.println("找零:" + (amount - price) + " 元");
in.close();
關鍵點:
System.out.print vs println:前者無換行,適合提示語;後者換行,適合結果輸出。nextInt() 只讀數字,**不消費換行符**;後續若用 nextLine() 必須先調用一次 nextLine() 吃掉殘留換行。if (in.hasNextInt()) { ... } else { System.err.println("請輸入整數!"); in.next(); }| 錯誤代碼 | 現象 | 原因 | 修正 |
|---|---|---|---|
| int a; System.out.println(a); | 編譯錯誤 | 局部變量未初始化 | 聲明時賦默認值:int a = 0; |
| final int b; b = 10; b = 20; | 編譯錯誤 | final 變量只能賦值一次 | 去掉 final 或只賦值一次 |
| Scanner in = new Scanner(System.in); in.nextInt(); in.nextLine(); | 讀到空字符串 | nextInt 留下換行符 | 中間加 in.nextLine(); 消費換行 |
| String s = "a" + 1 + 2; | s="a12" | 左到右字符串連接 | 用括號:"a" + (1+2) → "a3" |
userAge 而非 a。final 修飾不變量,利於編譯器優化與代碼可讀性。BigDecimal 或「分為單位的 long」避免浮點誤差。