Scanner类
Scanner
我们通过要从键盘读取输入前都要创建输入流对象 Scanner input = new Scanner(System.in);
Scanner 是一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。
Scanner(InputStream source)构造了一个新的 Scanner,它生成的值是从指定的输入流扫描的。其中InputStream 为输入流。
in 是标准的输入流 对应的设备就是键盘
创建输入流对象也可以这么写:
InputStream in = System.in;//System.in 为InputStream 类型
Scanner input = new Scanner(in);
判断输入类型
Scanner对象除了能过从键盘输入基本的数据类型(nextXXX()方法)外还可以用来判断输入的类型。
hasXXX()方法可以用来判断输入的数据类型是否为XXX,他会返回一个布尔类型
例如 boolean b = scanner.hasNextInt(); 若输入为Int型则b为true
下面例子为判断输入是否为Int型
public static int getNumber(){
int num = 0;
while (true) {
if (sc.hasNextInt()) {
num = sc.nextInt();
break;
} else {
sc = new Scanner(System.in);//为了阻塞住程序
System.out.println("你输入的类型不正确,请重新输入");
}
}
return num;
}
public class test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
int number = ScannerUtils.getNumber();
System.out.println(number);
}
}
注意 上边每次需要重新输入时都要创建一个新的Scanner对象用来阻塞程序,否则程序会一直判断输入为其他类型值,新的值不能从键盘输入进去。
输入字符串
Scanner 对象有两个输入字符串的对象 nextLine() 和next()方法
他俩区别在于若之前输入类基本类型数据,则nextLine()方法会读取基本类型数据后的回车,而不会读取需要输入的字符串
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入一个整数");
int num = sc.nextInt();
System.out.println("请输入一段字符串");
String s = sc.nextLine();
System.out.println(s);
System.out.println(num);
}
}
在上边程序中若你想输入123 abc 时,你的按键为123‘\n’456’\n’(回车键为’\n’)num会读取123,而’\n’会留在输入流中被s读取,而s读取到回车后就会停止读取,所有456不会输入到s中。
而如果将nextLine()方法换为next()方法就不会出现这样的问题。