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