简体   繁体   English

从文件Java中检测特定的字符串值

[英]Detecting a particular string value from a file, Java

I'm trying to detect a particular string value in an external txt file. 我正在尝试检测外部txt文件中的特定字符串值。 In this case, I am trying to detect %%. 在这种情况下,我试图检测%%。

public void read(){
    while(x.hasNext()){
        String a = x.next();
        System.out.println(a);
        if(a == "%%"){
            System.out.println("Found the end");
        }
        else{
            System.out.println("No end");
        }

    }
}

It is reading x correctly because it prints out the words from the file, but it says "No end" after every word, even the "%%". 它正在正确读取x,因为它会打印出文件中的单词,但在每个单词之后都显示“ No end”,即使是“ %%”也是如此。 I'm sure I am making some dumb mistake somewhere, I just can't find it. 我确定我在某个地方犯了一些愚蠢的错误,但我只是找不到。 x looks like this: apple orange %% grapes. x看起来像这样:苹果橙%%葡萄。 Any help with this would be appreciated. 任何帮助都将不胜感激。

You have to use String::equals() for comparison but not the operator == . 您必须使用String::equals()进行比较,但不能使用运算符== The == operator compares the address location of String and the string literal %% in your case. ==运算符将String的地址位置和字符串文字%%进行比较。

Try 尝试

    if(a.trim().equals("%%"))
    {
        System.out.println("Found the end");
    }

That should get rid of any excess whitespace at the end of the string as well as ensure a good comparison! 那应该消除字符串末尾的多余空格,并确保良好的比较!

You should use logical eqality using equals method rather than == which check for reference . 您应该使用equals方法而不是==来检查参考的逻辑等式。

if(a.equals("%%")){
        System.out.println("Found the end");
    }
    else{
        System.out.println("No end");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM