java如何读取键盘输入呢?
下文笔者将介绍使用java代码读取键盘输入的方法分享,如下所示:
System.in的read方法
例:public static void input1() throws IOException { int i = System.in.read(); System.out.println(i); } 注意事项: 以上方法只可以读取一个字符,并且必须是一个字符类型
方法2:InputStreamReader和BufferedReader方法
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类
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); } 注意事项: 这是我们常用的方法,此类不但可以读取键盘输入,还可以读取文件
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。