[英]Why findInLine(token) works but hasNext(token) doesn't
I am trying to understand the Scanner class and its methods. 我试图了解Scanner类及其方法。 I have understood how
findInLine
method works but I can't understand how hasNext(String)
and next(String)
methods work. 我已经了解
findInLine
方法如何工作,但是我不了解hasNext(String)
和next(String)
方法如何工作。
Here's my code. 这是我的代码。
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
hasNextTest("\\d");
//findInLineTest("\\d");
}
public static void findInLineTest(String token) {
Scanner s = new Scanner(System.in);
System.out.println("Input source string :");
System.out.flush();
String str = null;
while (( str = s.findInLine(token)) != null) {
System.out.println(str);
}
System.out.flush();
s.close();
}
public static void hasNextTest(String token) {
Scanner s = new Scanner(System.in);
System.out.println("Input source string :");
System.out.flush();
System.out.println(s.hasNext(token));
// while (s.hasNext(token)) {
// System.out.println(s.next(token));
// }
System.out.flush();
s.close();
}
}
The part I can't understand is if I pass to the scanner String "abcd12345abcd" or say any other String that has digits, the method hasNext("\\\\d")
doesn't return true. 我无法理解的部分是,如果我将其传递给扫描程序字符串“ abcd12345abcd”或说任何其他具有数字的字符串,则
hasNext("\\\\d")
不会返回true。 It doesn't return true
for any pattern and Strings for which the hasNext(String)
method should return true. 它不
return true
的任何图案和字符串其中hasNext(String)
方法应返回true。 I'm not using the Scanner object correctly but can someone help me find the mistake. 我没有正确使用Scanner对象,但是有人可以帮助我找到错误。
Thanks. 谢谢。
hasNext(pattern)
attempts to match the specified pattern against entire tokens. hasNext(pattern)
尝试将指定的模式与整个令牌进行匹配。 The string "abcd12345abcd" does not have delimiters, so it constitutes one token. 字符串“ abcd12345abcd”没有定界符,因此它构成一个标记。 Your pattern looks for a token consisting of a single digit, which obviously isn't going to match.
您的模式会寻找由一位数字组成的令牌,这显然不会匹配。
findInLine(pattern)
, on the other hand, attempts to find a pattern anywhere in the line, so the first found digit would match. 另一方面,
findInLine(pattern)
尝试在行中的任何位置查找模式,因此找到的第一个数字将匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.