基本輸出方法
Java 使用 System.out 物件來負責標準輸出(通常是畫面/終端機)。
print vs println
| 方法名 |
說明 |
System.out.print() |
輸出內容,不換行 |
System.out.println() |
輸出內容並換行 |
範例程式碼
1 2 3 4 5 6 7 8 9 10
| System.out.print("Hello "); System.out.print("World");
System.out.println("Hello"); System.out.println("World");
|
基本輸入方法(使用 Scanner 類別)
Java 沒有像 Python 那樣內建的簡單輸入函數,需要先引用 java.util.Scanner 類別。
使用步驟
import java.util.Scanner;
- 建立 Scanner 物件 →
Scanner sc = new Scanner(System.in);
- 呼叫對應方法讀取輸入內容(例如:
nextInt()、nextLine())
常見輸入方法與說明
| 方法 |
資料型態 |
範例輸入 |
next() |
字串(不含空白) |
abc |
nextLine() |
字串(含空白) |
abc def |
nextInt() |
整數 |
123 |
nextDouble() |
浮點數 |
12.34 |
nextBoolean() |
布林 |
true 或 false |
Scanner 範例程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import java.util.Scanner;
public class InputExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
System.out.print("請輸入姓名:"); String name = sc.nextLine();
System.out.print("請輸入年齡:"); int age = sc.nextInt();
System.out.println("你好," + name + ",你今年 " + age + " 歲。");
sc.close(); } }
|
注意事項
1 2 3
| int age = sc.nextInt(); sc.nextLine(); String name = sc.nextLine();
|
常見錯誤
| 錯誤描述 |
原因說明與解法 |
InputMismatchException 發生 |
輸入的資料型態不符(如輸入文字給 nextInt()) |
nextLine() 沒讀到資料 |
前面用了 nextInt(),未清除換行符號 |
| 輸入一直沒反應 |
沒有 System.out.print() 提示使用者輸入 |