Java的键盘输入方法

在工作中其实很少用到java读取键盘输入的情况,但是在各种网站刷题时却经常碰到,同时,在日常写一些测试方法的时候,如果通过键盘读取输入也是十分方便的,因此简要的做一个总结,方便后续查看及使用。

System.in的read方法

1
2
3
4
5
6
public static void input1() throws IOException {

int i = System.in.read();
System.out.println(i);

}

这种方式及其简单,但是只能读入一个字符,且必须是字符类型,输出int类型的话比较麻烦。但是可以比较方便的获取该字符的ascall码。

InputStreamReader和BufferedReader方法

1
2
3
4
5
6
public static void input2() throws Exception{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String name = br.readLine();
System.out.println("ReadTest Output:" + name);
}

输出结果如下:

这种方式可以读取一个字符串,但是如果需要读取int,float等类型仍需要自己转换。

Scanner类

1
2
3
4
5
6
7
8
9
10
11
12
public static void input3() throws Exception {

Scanner sc = new Scanner(System.in);

int i = sc.nextInt();//读取int
float f = sc.nextFloat();//读取float
String s = sc.nextLine();//读取字符串

System.out.println(i);
System.out.println(f);
System.out.println(s);
}

这种方式使用java5之后添加的Scanner类,Scanner类提供了读取int,float及字符串的方法,使用十分方便。

同时,Scanner不仅可以读取键盘输入值,也可以读取文件内容,只需要将构造方法中的数据来源切换成该文件即可。

参考链接

https://blog.csdn.net/u012249177/article/details/49586383


完。



ChangeLog

2018-11-11 完成

以上皆为个人所思所得,如有错误欢迎评论区指正。

欢迎转载,烦请署名并保留原文链接。

联系邮箱:huyanshi2580@gmail.com

更多学习笔记见个人博客——>呼延十