上星期在蓝桥杯考场上发现一个之前没有注意到的问题:Scanner类中的nextInt()、next()、nextLine()方法的使用。
首先没有注意到:next()方法读取字符串的时候在遇到空格、换行符的时候都会结束截止(在这里读取数据的时候,就已经宣告我这道题解不出了。。)
比完赛后百度,原来可以用nextLine(),这样读取字符串遇到空格就不会截止,而是等到回车。于是就写了下面这段代码进行验证。

1
2
3
4
5
6
7
8
public class A{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.nextInt();
String s = sc.nextLine();
System.out.print(s);
}
}

不过在输入第一个数字验证的时候呢出现了如下结果:

Scanner1
Scanner1

输入字符串的机会都不给我。。

这时我猜想,可能是写入了一个空字符或者转义字符之类的。这个时候我们去看官方文档:

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.

next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

每一次读取过程是从光标位置开始的。所以,一开始那个程序当我们输入4并按下回车,由于nextInt()方法只读取数值而不会读取换行符,所以光标停在了4和\n之间,于是nextLine()方法将4后面的换行符给读掉了,所以造成字符串s是一个换行符。

为了完成最后的输入,程序应该这样写:

1
2
3
4
5
6
7
8
9
public class A{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
sc.nextInt();
sc.nextLine(); //读取掉数字后面的换行符
String s = sc.nextLine();
System.out.println(s);
}
}

结果如下:

Scanner2
Scanner2