I'm at a loss here.
I'm tying to read text from standard input and then play with the string
in an if statement, but for some reason, the if statement won't take it.
Here's the snippet of code:
/*********************/
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
"Blah" is never printed out even if "selection" really does equal "a".
It DOES work though, if I set "selection" to "a" before the if statement.
The if statement acts as if "selection" is null, but when I change the condition
to, "if( selection != null)", then it is accepted and prints out "blah" like
it's supposed to.
It also works if I use numeric values rather than strings.
Anyone know what the problem is?
10-16-2000, 11:02 AM
Paul Clapham
Re: Text input
This is a common error. To compare Strings for equality, use the equals()
method, like so:
if (selection.equals("a"))
When you use "==", you are comparing to see if the two sides refer to the
same object. In your case, they refer to different String objects that
contain the same data. This is a general rule in Java for all objects.
(And that's why it works with numeric values, because they aren't objects.)
PC2
kleric <kleric_@hotmail.com> wrote in message
news:39ea83d0$1@news.devx.com...
>
> I'm at a loss here.
> I'm tying to read text from standard input and then play with the string
> in an if statement, but for some reason, the if statement won't take it.
> Here's the snippet of code:
>
> /*********************/
> public static void main(String[] args) throws IOException {
> BufferedReader stdin = new BufferedReader
> (new InputStreamReader(System.in));
>
>
> while(true){
>
> String selection = stdin.readLine();
>
> if( selection == "a") {
> System.out.println("blah");
> }
>
> }
> }
> /***********************/
>
> "Blah" is never printed out even if "selection" really does equal "a".
> It DOES work though, if I set "selection" to "a" before the if statement.
> The if statement acts as if "selection" is null, but when I change the
condition
> to, "if( selection != null)", then it is accepted and prints out "blah"
like
> it's supposed to.
> It also works if I use numeric values rather than strings.
> Anyone know what the problem is?
>