1

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.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Mr.Y
  • 855
  • 2
  • 10
  • 14
  • The second point is because pressing just enter gives you "\n", but since readLine method deletes the "\n" at the end you just get "" (an empty string), which is different form null. For the first one, just check the answers. – raven1981 Sep 22 '12 at 22:42

3 Answers3

3

Change:

buf != "doh"

to:

!buf.equals("doh")

And read: Java String.equals versus ==.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

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.

gkuzmin
  • 2,414
  • 17
  • 24
2

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();
    }
}
arshajii
  • 127,459
  • 24
  • 238
  • 287