首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 100例:標準輸入輸出與簡易命令列處理

     編輯:Java 程式設計入門

示範使用 System.in、BufferedReader 讀取鍵盤輸入,搭配 Vector 儲存資料,實作簡易互動式命令:in:內容 新增、out 列印、quit 結束。

import java.util.*;
import java.io.*;

public class StdIO {
    public static void main(String[] args) {
        Vector data = new Vector<>();
        boolean running = true;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (running) {
            System.out.print("input> ");
            String line;
            try { line = in.readLine(); }
            catch (IOException e) { System.err.println("IO error!"); continue; }

            String cmd = "", ctx = "";
            int idx = line.indexOf(':');
            if (idx == -1) cmd = line.trim();
            else { cmd = line.substring(0, idx); ctx = line.substring(idx+1); }

            if (cmd.equalsIgnoreCase("in")) {
                if (ctx.isEmpty()) System.err.println("格式錯誤!");
                else data.add(ctx);
            } else if (cmd.equalsIgnoreCase("out")) {
                for (int i = 0; i < data.size(); i++)
                    System.out.println(i + ": " + data.get(i));
            } else if (cmd.equalsIgnoreCase("quit")) {
                running = false;
            } else {
                System.err.println("未知指令:" + cmd);
            }
        }
    }
}

重點:

  • System.in 為 InputStream,需包裝 InputStreamReader 再包裝 BufferedReader 才能按行讀取。
  • Vector 為舊版集合,現代建議使用 ArrayList。
  • 命令解析採用簡單冒號分隔,實務上可使用 Scanner 或命令列解析庫 (如 Picocli)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved