如代码显示,若用nextLine()读取字符串元素,且前面使用了nextInt(),则字符串元素会少读一个。
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strings = new String[n];
for(int i = 0; i < n; i++) {
strings[i] = in.nextLine();
}
如图显示,按逻辑应该读入四个字符串才对,可读取完第三个字符串后程序就停止了。
在strings[i] = in.nextLine()后加上System.out.println(strings[i])语句,查看输出后会发现出在4与1111之间出现了一行空白,也就说明在我们还没有输入字符串时,字符串数组就读取了一个字符串。
查阅资料后明白是因为nextInt()读取完整数后会留下光标(换行符或者回车符),而nextLine()读取的字符串包含其末尾的光标,如果只有一个光标也读取它。所以在上述程序中,nextLine()读取了nextInt()留下的回车,这就是为什么程序只读取了三个字符串,且输出了一个空行的原因。
如果只是读取一行连续的字符串,则可以将nextLine()换成next(),因为next()在读取时,会过滤掉有效字符前后的无效字符,对输入有效字符之前遇到的空格键、Tab键或Enter键等,next()会自动将其过滤掉;读取完有效字符之后,next()也会过滤末尾后的空格键、Tab键或Enter键等
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strings = new String[n];
for(int i = 0; i < n; i++) {
strings[i] = in.next();
}
或者我们可以在nextInt()与nextLine()之间加上一条nextLine(),去把nextInt()遗留下的回车读取掉
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] strings = new String[n];
for(int i = 0; i < n; i++) {
strings[i] = in.next();
}
之后发现,nextDouble(), nextFloat(), nextLong()等都会留下光标造成上述问题,解决办法还是一样的。