有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解findWithinHorizon输出

使用Scanner类玩时,我编写了这段代码来查看findWithinHorizon的行为,但是,我无法确切地解释为什么输出中缺少某些模式

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Main {

    public static void main(String[] args) throws FileNotFoundException {

        FileInputStream FS = new FileInputStream("dummy.txt");
        Scanner scanner = new Scanner(FS);
        int counter = 0;
        while (scanner.hasNext()) {
            counter++;
            String P = scanner.findWithinHorizon(scanner.next(),100);
            if (P!=null)
                System.out.println(counter+" "+P);
        }
    }
}

我的dummy.txt文件包含以下文本:

On her way she met a copy. The copy warned the Little Blind Text, that where it came from it would have been rewritten a thousand times and everything that was left from its origin would be the word "and" and the Little Blind Text should turn around and return to its own, safe country.

上面的代码打印出来

2 her
3 e
4 from
5 its

这很清楚。我不明白的是,为什么输出中没有单词copy?另外,在试图理解此方法的机制时,我意识到地平线实际上是字符数(来自Javadoc:无分隔符)。但是scanner.next()呢?它是否将迭代器移动到下一个字符或下一个单词?如果是前者,结果中如何包含单词(例如,她的


共 (1) 个答案

  1. # 1 楼答案

    1)“copy”不在那里的原因是因为Scanner.findWithinHorizon()也推进令牌。 见文件http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

    “如果找到该模式,扫描仪将通过匹配的输入并返回匹配该模式的字符串。”

    因此,当发现“她”时,它会跳过原始的“复制”标记

    2)Scanner.next()将迭代器移动到下一个标记(默认情况下由“”删除)

    3)“她的”是从w“她的”e中找到的