输入字符串
_ _ _ _one _ two\n // "_"表示空格,"\n"表示回车
未设置useDelimiter()的情况
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
输出字符串str得到"one",str.length()等于3,可知最后的"\n"并未扫描进来
设置useDelimiter("\n");的情况
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
String str = scanner.next();
输出字符串str得到"_ _one _ two",长度为12,可知最后的"\n"被扫描进来了
这是为什么呢?
Under Windows, when we press the
Enter
key on the keyboard, we actually enter two characters: carriage return and line feed:rn
, and the ASCII codes are13和10
By default, the input obtained by
Scanner
does not contain carriage returns and line feeds. For example, if you enter____one_tworn
, it will only get the output from____one_two
(of course, it may have to be obtained through multiplenext()
s), and automatically filter out carriage returns and line feedsBut when we force carriage return or line feed as the delimiter, it will not automatically filter the carriage return and line feed. For example, if you use the carriage return character
n
as the separator, entering the above content will result in____one_twor
, which is why the returnedlength
is 12. You can use the following program to verify it. You can find that the ASCII code of the last character in the obtained string is 13, which means it is a carriage return characterr
:Solution: Use
rn
as the delimiter and it will be normalEnter under Windows is rn