Reputation:
Not sure if I've missed something really obvious. I know for sure that my String
is as follows:
1This is a test message
I'm trying to detect whether the first character is '1', so here's some of my code:
//This outputs '1'
Toast noCmd = Toast.makeText(Play.this, decodedMessage.substring(0,1), Toast.LENGTH_SHORT);
noCmd.show();
if (decodedMessage.charAt(0) == 1) {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
if (decodedMessage.substring(0,1) == "1") {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
As you can see, I'm trying two methods to get the toasts inside the if statement to show up. Weirdly, when the code is run, only the top (unconditional) toast displays.
Any ideas?
Upvotes: 0
Views: 230
Reputation: 20520
For the first one, the char
is '1'
. What's currently happening in your code is that because you're comparing a char
with an integer, the char
is being converted to an int
using its character code. For a 1
, that comes out as 49, which is not equal to the integer 1. You need to compare the char
you're retrieving from the String
with the char
representing a digit "1", and that means you need to write it as '1'
.
For the second one, you need to use .equals()
to test for String
equality, rather than ==
. If you take two String
objects s
and t
that have the same content, then you still will find that s==t
will come out as false, unless they happen to be pointing at the same bit of memory (i.e., they're the same instance). To check whether they have the same content, you check
s.equals(t)
rather than
s==t
So, in summary, make the first one
if (decodedMessage.charAt(0) == '1') {
//toast stuff
}
and the second one
if ("1".equals(decodedMessage.substring(0,1))) {
//toast stuff
}
The reason, by the way, for not writing
if (decodedMessage.substring(0,1).equals("1")) {
//toast stuff
}
instead is that if the String
on which you call .equals()
is null
then you'll end up with a NullPointerException
, which usually you want to avoid. Actually in this case it would be fine, because the substring()
call won't return null
, but in the general case if you want to test whether s
and "something"
are equal then you use
"something".equals(s)
rather than
s.equals("something")
just in case s
is null
.
Upvotes: 1
Reputation: 152867
1
is an integer with value 1. If you want the ASCII 1
, use '1'
in single quotes which has the integer value of 49.
For comparing strings, use equals()
and not ==
. See How do I compare strings in Java?
Upvotes: 1
Reputation: 6857
To compare strings you need to use equals
method:
if("1".equals(decodedMessage.charAt(0))){
}
Upvotes: 0