最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java怎么读取键盘输入?Java中接收键盘输入的三种方法
时间:2017-02-16 编辑:简简单单 来源:一聚教程网
代码如下 | 复制代码 |
importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStreamReader; importjava.util.Scanner;
publicclassEnterTest {
publicstaticvoidmain(String[] args) {//主方法 CharTest(); //调用System.in方法 ReadTest(); //调用ReadTest方法 ScannerTest();//调用ScannerTest方法 } /** * System.in和System.out方法 * 缺点一: 该方法能获取从键盘输入的字符,但只能针对一个字符的获取 * 缺点二: 获取的只是char类型的。如果想获得int,float等类型的输入,比较麻烦。 */ publicstaticvoidCharTest(){ try{ System.out.print("Enter a Char:"); chari = (char)System.in.read(); System.out.println("Yout Enter Char is:"+ i); } catch(IOException e){ e.printStackTrace(); }
} /** * InputStreamReader和BufferedReader方法 * 优点: 可以获取键盘输入的字符串 * 缺点: 如何要获取的是int,float等类型的仍然需要转换 */ publicstaticvoidReadTest(){ System.out.println("ReadTest, Please Enter Data:"); InputStreamReader is =newInputStreamReader(System.in);//new构造InputStreamReader对象 BufferedReader br =newBufferedReader(is);//拿构造的方法传到BufferedReader中 try{//该方法中有个IOExcepiton需要捕获 String name = br.readLine(); System.out.println("ReadTest Output:"+ name); } catch(IOException e){ e.printStackTrace(); }
} /** * Scanner类中的方法 * 优点一: 可以获取键盘输入的字符串 * 优点二: 有现成的获取int,float等类型数据,非常强大,也非常方便; */ publicstaticvoidScannerTest(){ Scanner sc =newScanner(System.in); System.out.println("ScannerTest, Please Enter Name:"); String name = sc.nextLine(); //读取字符串型输入 System.out.println("ScannerTest, Please Enter Age:"); intage = sc.nextInt(); //读取整型输入 System.out.println("ScannerTest, Please Enter Salary:"); floatsalary = sc.nextFloat();//读取float型输入 System.out.println("Your Information is as below:"); System.out.println("Name:"+ name +"\n"+"Age:"+age +"\n"+"Salary:"+salary); } } |
总结:
要获取键盘中的输入:
python提供了,python2中有raw_input(),python3中有input()。
c提供了scanf()函数
c++提供cin()函数来获取键盘输入
java中没有现成的函数来获取键盘输入,但仍然可以用上述方法来实现,其中方法三应该是最简单,最方便的。
相关文章
- Python 读取天气预报例子 02-23
- Word怎么读生僻字 巧用Word 读取生僻字 09-23
- 下班前一贴,用wsh读取registry. 01-18
- 我要直接读取请求的信息头,我要怎么做? 01-12
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24