public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个整数值:");
int intValue = sc.nextInt();
System.out.println("intValue = " + intValue);
System.out.println();
System.out.println("请输入一个字符串");
String strValue = sc.nextLine();
System.out.println("strValue = " + strValue);
}
}
运行结果:
控制台并没有阻塞让输入。
原因是在调用sc.nextInt(); 方法时最后一个控制字符是回车,输入了1和回车实际上是把这两个字符共同发送到了scanner的输入缓冲区中,而nextInt只会读取int类型,回车符不会读取,但是在调用nextLine方法时只要遇到回车符就结束,此时读取到的实际上是nextInt方法最后的一个回车,在输入缓冲区中。所以nextLine既然读到了内容,则不会再阻塞。
- 解决
在nextInt之后手动再调用一个nextLine消耗掉输入缓冲区中的换行符即可。