首页 > 技术文章 > 还债——Java获取键盘输入的三种方法

SkyeAngel 2018-03-25 10:50 原文

Java基础——输入输出

1.System.in.read()  获取一个字符char

public static void main(String[] args) throws IOException {
        char ch = (char)System.in.read();
        System.out.println(ch);
    }

  

要注意的是:1.要有异常处理 IOException

2.只能获取单个字符 char型

3.注意强制类型转换

2.BufferedReader 和 InputStreamReader  获取 字符串  readLine()

public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String str = bufferedReader.readLine();
        System.out.println(str);
    }

  

需要注意的依然是:要有异常处理,还有读取字符串,只能用readLine()

 

3.Scanner类(推荐)

 

import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        System.out.println(str);
        int num = in.nextInt();
        System.out.println(num);
        long num1 = in.nextLong();
        System.out.println(num1);
        while(in.hasNext()){
            System.out.println(in.next());
        }
    }
}

 

  

 

 注意:使用Scanner类的时候,很轻松的接收到输入的东西  next(), nextInt(), nextFloat(), nextLong() 还有nextLine() 

但是nextLine(),与next()的区别是:

next()在接收有效数据前不接收tab 空格 或者enter,在接收到有效数据后,则遇到这些键就退出

nextLine()接收空格,tab,应该以enter结束

 

java中数组初始化的方法

还债——Java数组初始化

 

推荐阅读