【问题标题】:List of Strings - Odd Behavior字符串列表 - 奇怪的行为
【发布时间】:2015-03-10 01:00:09
【问题描述】:

我正在为随机单词生成器开发一个淫秽过滤器,以便它避免某些单词或短语。到目前为止,代码相当简单,我正在使用一些测试词来尝试它,但是已经发生了一个奇怪的错误,这对我来说完全没有意义。

final List<String> obscene;

WordEngine(){
    obscene = new ArrayList<>();
    loadObscene();
    System.out.println(isObscene("otestingo"));
}

void loadObscene(){
    try {
        InputStream configStream = Interactions.class.getResourceAsStream("obscene.txt");
        Scanner fileScanner = new Scanner(configStream);
        fileScanner.useDelimiter("\\n");
        String nextWord;
        while(fileScanner.hasNext()){
            nextWord = fileScanner.next();
            obscene.add(nextWord);
        }
    }catch(Exception e){
        System.out.println(e);
    }
    //for(String obsceneIterator : obscene){ System.out.println(obsceneIterator); }
}

boolean isObscene(String word){
    for (Iterator<String> it = obscene.iterator(); it.hasNext();) {
        String nextObscene = it.next();
        String test = nextObscene;
        System.out.println(test);
        System.out.println(test + " " + word);
        if(word.contains(nextObscene)){
            return true;
        }
    }
    return false;
}

文本文件包含:

words
for
testing

输出是:

words
otestingo
for
otestingo
testing
otestingo
false

预期的输出是:

words
words otestingo
for
for otestingo
testing
testing otestingo
true

关于连接字符串或访问它的某些事情导致它被删除。我已经尝试了我能想到的所有类型的探索,但没有找到任何方法来理解我所期望的和我得到的之间的差异。

【问题讨论】:

    标签: java java.util.scanner contains string-concatenation


    【解决方案1】:

    在您的文本文件中使用 UNIX 行尾 (\n) 时,您的程序会产生您期望的输出。但是,如果您使用 dos 行结尾,您(几乎)会得到您描述的输出。我看到的真实输出是:

    words
     otestingo
    for
     otestingo
    testing
     otestingo
    false
    

    您可能不在 UNIX 衍生操作系统上 - 而且我不知道转换行尾的 Windows 工具是什么 - 但如果您有 Vim,您可以使用命令 ff=unix 并将文件写回以进行更改行尾。

    或者,您可以简单地删除此行:

    fileScanner.useDelimiter("\\n");
    

    ...扫描器将正确处理您的 dos 行结尾。

    【讨论】:

    • 尊重。你是怎么想出来的?!
    • 当程序为我工作时,我有一种预感,文本文件可能有非 UNIX 行结尾。
    • 哇!非常感谢!我知道有一些额外的信息以某种方式存储在那个字符串中导致了奇怪的输出,我知道它与扫描仪有关。我从没想过是我的分隔符导致了这个问题。我在 Windows 8 上运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2020-06-18
    • 2015-05-29
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多