简体   繁体   中英

Detecting a particular string value from a file, Java

I'm trying to detect a particular string value in an external txt file. 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 "%%". I'm sure I am making some dumb mistake somewhere, I just can't find it. x looks like this: apple orange %% grapes. Any help with this would be appreciated.

You have to use String::equals() for comparison but not the operator == . The == operator compares the address location of String and the string literal %% in your case.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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