public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入一个整数:");
int i = sc.nextInt();
System.out.println(i);
System.out.println("输入字符串");
String next = sc.nextLine();
System.out.println(next);
}
}
结果:
输入一个整数:
10
10
输入字符串
Process finished with exit code 0
先nextInt然后nextLine会遇到这个Bug,无法录入字符串的情况会发生。
原因参考如下:
Scanner的bug
解决办法:
1.在录入字符串(nextLine)之前写一个nextLine()去读取掉缓存中的换行符即可。
2.将nextLine替换成next,但是next有弊端,如果字符串中有空格(转义字符等),它只能读取到空格之前的部分。