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

Java 控制台輸入掃描:Scanner 與 BufferedReader 完整範例

     編輯:Java 相關知識

標準輸入讀取兩大主流類別實戰

針對競技程式設計、CLI 工具、批次處理,Scanner 與 BufferedReader 是最常用的輸入工具。

1. Scanner (java.util) - 功能豐富、型別安全

import java.util.Scanner;

public class ScannerInputDemo {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        
        // 讀取整數
        System.out.print("輸入整數 n: ");
        int n = sc.nextInt();
        
        // 讀取字串 (以空白分隔)
        System.out.print("輸入字串: ");
        String s = sc.next();
        
        // 讀取整行 (含空白)
        System.out.print("輸入整行: ");
        sc.nextLine(); // 消耗換行符
        String line = sc.nextLine();
        
        System.out.println("n=" + n + ", s=" + s + ", line=" + line);
    }
}

Scanner 進階:檔案掃描與型別檢查

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

public class ScannerFileSum {
    public static void main(String[] args) throws IOException {
        // 建立測試檔案
        try (FileWriter fw = new FileWriter("num.txt")) {
            fw.write("2 2.2 3.3 3.33 4.5 done");
        }
        
        // 掃描求和
        double sum = 0;
        try (Scanner sc = new Scanner(new File("num.txt"))) {
            while (sc.hasNext()) {
                if (sc.hasNextDouble()) {
                    sum += sc.nextDouble();
                } else {
                    String token = sc.next();
                    if ("done".equals(token)) break;
                    else throw new RuntimeException("格式錯誤: " + token);
                }
            }
        }
        System.out.println("Sum = " + sum); // 15.33
    }
}

2. BufferedReader (java.io) - 高效能、逐行讀取

import java.io.*;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.print("輸入一行文字: ");
            String line = br.readLine(); // 阻塞直到換行
            System.out.println("您輸入: " + line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedReader 讀取檔案全內容

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

效能與功能對比

維度ScannerBufferedReader
讀取速度 (大量資料)較慢 (解析開銷)極快 (單純緩衝)
型別自動解析支援 (nextInt, nextDouble...)不支援 (需手動 parse)
正則分隔符支援 useDelimiter()不支援
記憶體佔用略高極低
適用場景互動式輸入、混合型別、檔案解析大檔案逐行、高效能需求、競技程式

競技程式設計輸入模板

// 快速輸入模板 (BufferedReader + StringTokenizer)
import java.io.*;
import java.util.*;

public class FastInput {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;
    
    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(br.readLine());
        }
        return st.nextToken();
    }
    static int nextInt() throws IOException { return Integer.parseInt(next()); }
    static long nextLong() throws IOException { return Long.parseLong(next()); }
    static double nextDouble() throws IOException { return Double.parseDouble(next()); }
    
    public static void main(String[] args) throws IOException {
        int n = nextInt();
        long sum = 0;
        for (int i = 0; i < n; i++) sum += nextLong();
        System.out.println(sum);
    }
}

最佳實踐建議

  • 競技程式/大資料:BufferedReader + StringTokenizer 或 Java 8+ Stream 處理。
  • 互動式 CLI / 型別混合:Scanner 開發效率最高。
  • 檔案解析:Scanner 針對結構化文字;BufferedReader 針對行導向日誌。
  • 記得使用 try-with-resources (JDK 7+) 自動關閉資源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved