Java:对Scanner的useDelimiter()方法的疑问
迷茫
迷茫 2017-04-17 15:19:12
0
2
392

输入字符串

_ _ _ _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"被扫描进来了

这是为什么呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
PHPzhong
  1. 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 are 13和10

  2. 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 multiple next()s), and automatically filter out carriage returns and line feeds

  3. But 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 returned length 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 character r:

// 输入`____one_two\r\n`来测试
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
String str = scanner.next();
// 打印获取到的内容和其长度,以及最后一个字符的ASCII码
System.out.println(str + ":" + str.length()
        + " (" + str.codePointAt(str.length()-1) + ")");

Solution: Use rn as the delimiter and it will be normal

伊谢尔伦

Enter under Windows is rn

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!