Java.util.Scanner.hasNext() 方法
描述
如果下一个完整标记与指定模式匹配,则 java.util.Scanner.hasNext(Pattern pattern) 方法返回 true。 完整的标记由匹配分隔符模式的输入添加前缀和后缀。 此方法可能会在等待输入时阻塞。 扫描仪不会超过任何输入。
声明
以下是 java.util.Scanner.hasNext() 方法的声明
public boolean hasNext(Pattern pattern)
参数
pattern − 要扫描的模式
返回值
当且仅当此扫描器具有与指定模式匹配的另一个标记时,此方法才返回 true
异常
IllegalStateException − 如果此扫描仪已关闭
示例
下面的例子展示了 java.util.Scanner.hasNext() 方法的使用。
package com.tutorialspoint;
import java.util.*;
import java.util.regex.Pattern;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// check if the scanner's next token matches "rld" following 2 chars
System.out.println("" + scanner.hasNext(Pattern.compile("..rld")));
// check if the scanner's next token matches "llo" following 2 chars
System.out.println("" + scanner.hasNext(Pattern.compile("..llo")));
// print the rest of the string
System.out.println("" + scanner.nextLine());
// close the scanner
scanner.close();
}
}
让我们编译并运行上面的程序,这将产生以下结果 −
false true Hello World! 3 + 3.0 = 6

