JVM 啟動時自動將標準輸入綁定到 System.in(InputStream)。使用者輸入文字按 Enter,OS 將資料送入此流,程式呼叫 read() 即可獲取。
byte[] buf = new byte[1024];
int len = System.in.read(buf); // 阻塞直到有輸入
String s = new String(buf, 0, len - 2); // 扣除 \r\n (Windows)
System.out.println("輸入:" + s);
byte[] buf = new byte[1024];
while (true) {
System.out.print("請輸入:");
int len = System.in.read(buf);
String s = new String(buf, 0, len - 2); // 處理換行
if ("quit".equalsIgnoreCase(s)) break;
System.out.println("回顯:" + s);
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = br.readLine()) != null) { // null 表示 EOF
if ("quit".equals(line)) break;
System.out.println("回顯:" + line);
}
}
readLine() 自動處理跨平台換行符,不含換行符,碼更乾淨。
import java.io.*;
public class DiceGame {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int money = 1000;
while (true) {
// 1. 押大小
int type = readInt(br, "請押大小(1大/2小):", v -> v==1||v==2);
// 2. 下注金額
int bet = readInt(br, "當前金額 " + money + ",請下注:",
v -> v > 0 && v <= money);
// 3. 擲骰子
int diceSum = rollDice();
// 4. 判定勝負
boolean win = (diceSum <= 9 && type == 2) || (diceSum >= 10 && type == 1);
// 5. 結算
money += win ? bet : -bet;
System.out.println("剩餘金額:" + money);
if (money <= 0) {
System.out.println("你輸光了,Bye!");
break;
}
}
}
// 通用整數輸入驗證方法
static int readInt(BufferedReader br, String prompt, java.util.function.IntPredicate validator) throws IOException {
while (true) {
System.out.print(prompt);
String line = br.readLine();
try {
int val = Integer.parseInt(line.trim());
if (validator.test(val)) return val;
} catch (NumberFormatException ignored) {}
System.out.println("輸入非法,請重新輸入!");
}
}
static int rollDice() {
int d1 = (int)(Math.random()*6)+1;
int d2 = (int)(Math.random()*6)+1;
int d3 = (int)(Math.random()*6)+1;
System.out.println("莊家開:" + d1 + " " + d2 + " " + d3 + " = " + (d1+d2+d3));
return d1+d2+d3;
}
}
請押大小(1大/2小):1 當前金額 1000,請下注:200 莊家開:4 5 2 = 11 莊家開大! 剩餘金額:1200 請押大小(1大/2小):2 當前金額 1200,請下注:500 莊家開:1 2 3 = 6 莊家開小! 剩餘金額:1700 ...
| 技術點 | 說明 |
|---|---|
| 阻塞式輸入 | read()/readLine() 無輸入時阻塞線程,釋放 CPU |
| 換行符處理 | Windows \r\n、Linux \n、Mac \r;readLine() 自動適配 |
| 編碼一致性 | InputStreamReader 指定 StandardCharsets.UTF_8 避免中文亂碼 |
| 輸入驗證模式 | 循環讀取 → 解析 → 校驗 → 失敗重試,封裝為通用方法 |
| 資源管理 | try-with-resources 確保 BufferedReader 關閉 |
控制台交互是「標準輸入/輸出流」的最簡形式。同樣的代碼結構,將 System.in 換成 Socket.getInputStream()、HttpServletRequest.getInputStream(),即可無縫遷移至網路程式。掌握流式讀取、緩衝、解碼、驗證四步法,是所有 IO 程式設計的通用內功。