Java中获取键盘输入值的三种方法
Java中从键盘获得数据的三种方式
第一种:
第一种最为常见和强大,通过 System.in 获取数据流,java.util.Scanner 工具将数据流转换为想要的数据。
import java.io.IOException;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) throws IOException {
System.out.println("请输入数据:");
Scanner sc = new Scanner(System.in);
//返回int型
int nextInt = sc.nextInt();
System.out.println("你输入的是: " + nextInt);
//返回double型
double nextDouble = sc.nextDouble();
System.out.println("你输入的是: " + nextDouble);
//返回一串字符串
String nextLine = sc.nextLine();
System.out.println("你输入的是: " + nextLine);
}
}
需要注意的是,调用了那种类型的方法,就必须输入这种类型的数据,否则可能会报转换错误异常 Exception in thread "main" java.util.InputMismatchException
第二种:
使用字符流和字符缓冲流获取数据,再读取字符流数据。
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
//字符缓冲流读取键盘输入数据
System.out.println("请输入数据:");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String readLine = bufferedReader.readLine();
System.out.println("你输入的数据是:" + readLine);
//字符流读取键盘输入数据
System.out.println("请输入数据:");
InputStreamReader reader = new InputStreamReader(System.in);
char[] buff = new char[1024];
int len = 0;
while ((len = reader.read(buff)) != -1) {
String s = new String(buff, 0, len);
System.out.println("你输入的数据是:" + s);
}
}
}
这里推荐字符缓冲流,比较方便。
第三种:
使用字节流接收数据,再读取字节流数据。
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
//字节缓冲流读取键盘输入数据
System.out.println("请输入数据:");
BufferedInputStream inputStream = (BufferedInputStream) System.in;
InputStream in = System.in;
byte[] buff = new byte[1024];
int len;
while (((len = inputStream.read(buff)) != -1)) {
System.out.println("您输入的数据是:" + new String(buff, 0, len));
}
}
}
System.in获取的是一个字节流,通过字节缓冲流接收,再输出。
我看有的博主使用了char c = System.in.read();接收一个键盘输入字节再输出出来的方法。其实这就是利用了读取字节流,使用char类型一次读取一个字节。
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
//字节流读取键盘输入数据
System.out.println("请输入数据:");
//一次只能读取一个字节,不能读取中文,因为一个中文占了两个字节
char c = (char) System.in.read();
System.out.println("你输入的是: " + c);
}
}
只会读取一个字节
中文无法读取,因为一个中文占据两个字节