java 獲取控制台輸入


讀取控制台輸入

從控制台讀取一行數據,返回值字符串

public class IO {
    public static void main(String args[]) throws IOException {
        // 使用 System.in 創建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'exit' to quit.");
        do {
            // 從控制台讀取一行數據,返回值字符串
            str = br.readLine();
            System.out.println(str);
            
        } while (!str.equals("exit"));
    }
}

從控制台讀取一行字符,read逐次返回單個字符

public static void main(String args[]) throws IOException {
    char c;
    // 使用 System.in 創建 BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("輸入字符, 按下 'q' 鍵退出。");
    // 讀取字符
    do {
        c = (char) br.read();
        System.out.println(c);
    } while (c != 'q');
}

Scanner 類

public class IO {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 判斷是否還有輸入
        while (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println(str2);
        }
        scan.close();
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM