Mr.Y
Mr.Y

Reputation: 875

BufferedReader readLine() - Exit when a specific string is entered

As title, I want it to exit the loop when I entered a specific keyword.

try {
    buf = br.readLine();
    while (buf != "doh") {
        buf = br.readLine();
    }
}

Two questions:

  1. When I enter doh from my command prompt, it doesn't exit the loop.

  2. If I put "buf != null" it works only if I press Ctrl+Z. If I enter nothing (just press enter key) it doesn't exit the loop.

Upvotes: 1

Views: 2259

Answers (3)

gkuzmin
gkuzmin

Reputation: 2474

Use equals method instead of !=. Operator != will return true only if references to object will not be identical. Method equal wil compare strings char by char.

Upvotes: 2

arshajii
arshajii

Reputation: 129497

You shouldn't compare strings (and objects in general) with ==, that is utilized only for primitives (int, char, boolean etc.). For objects, you use the equals method.

try {
    buf = br.readLine();
    while (! buf.equals("doh")) {
        buf = br.readLine();
    }
}

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

Change:

buf != "doh"

to:

!buf.equals("doh")

And read: Java String.equals versus ==.

Upvotes: 3

Related Questions