Reputation: 875
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:
When I enter doh
from my command prompt, it doesn't exit the loop.
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
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
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
Reputation: 340713
Change:
buf != "doh"
to:
!buf.equals("doh")
And read: Java String.equals versus ==.
Upvotes: 3