我是Java的新手并试图理解Scanner类.我正在使用示例代码来了解Scanner类的skip(String Pattern)方法.我稍稍调整了代码并将其更改为
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6.0 true ";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// changed the string to skip
scanner.skip("World");
// print a line of the scanner
System.out.println("" + scanner.nextLine());
// close the scanner
scanner.close();
}
}
Run Code Online (Sandbox Code Playgroud)
我期待的输出是
Hello ! 3 + 3.0 = 6.0 true
Run Code Online (Sandbox Code Playgroud)
但我明白了NoSuchElementException.有人可以指出我的错误.
这不是nextLine给你的例外,而是跳过("世界").
当扫描仪启动时,它指向"Hello Word ..."中的"H",这是第一个字母.
然后你告诉他跳过,并且必须为跳过给出一个正则表达式.
现在,一个好的正则表达式跳到"世界"这个词之后是:
scanner.skip(".*World");
Run Code Online (Sandbox Code Playgroud)
".*世界"的意思是"世界所遵循的每个角色".
这会将扫描仪移动到"!" 在"Hello World"之后,所以nextLine()将返回
! 3 + 3.0 = 6.0 true
Run Code Online (Sandbox Code Playgroud)
根据跳过,已跳过"Hello"部分.
| 归档时间: |
|
| 查看次数: |
4671 次 |
| 最近记录: |