Computer Science Canada Compare Two Strings in if Statement |
Author: | Mithokey [ Sat Apr 28, 2012 12:58 am ] | ||
Post subject: | Compare Two Strings in if Statement | ||
I keep on getting an error for the line where it says if (pepperoni == YES); Does anyone know how I can fix this? Thanks!
|
Author: | Tony [ Sat Apr 28, 2012 10:47 pm ] |
Post subject: | RE:Compare Two Strings in if Statement |
- what is the value of YES - will the entered string be the same object as the literal that you are comparing against? |
Author: | joshm [ Mon Apr 30, 2012 9:09 am ] |
Post subject: | RE:Compare Two Strings in if Statement |
pepperoni.equals("YES") |
Author: | wtd [ Tue May 01, 2012 1:21 am ] |
Post subject: | RE:Compare Two Strings in if Statement |
It is poor form to simply provide working code with no explanation. The best thing to do is to respond with leading questions, as Tony has done. Failing that, you could at least provide an explanation as to why your working code provides the desired result. |
Author: | TokenHerbz [ Tue May 01, 2012 8:09 pm ] |
Post subject: | RE:Compare Two Strings in if Statement |
//your code... //if (pepperoni == YES) { if (pepperoni == "YES") { //that works... //change all your YES to "YES"... |
Author: | DemonWasp [ Tue May 01, 2012 9:35 pm ] |
Post subject: | RE:Compare Two Strings in if Statement |
@Token: That doesn't (always) work right in Java -- Strings are compared by reference equality if you use ==. To compare by content, you need to use .equals(), like every other class in Java. |
Author: | TokenHerbz [ Mon May 07, 2012 12:13 am ] |
Post subject: | RE:Compare Two Strings in if Statement |
what if your checking a specific thing against something else specifically in memory, still better to use .equals()? |
Author: | Tony [ Mon May 07, 2012 1:03 am ] |
Post subject: | RE:Compare Two Strings in if Statement |
If you are checking to see that two objects point to the same location in memory, use ==. Though with strings, that is almost never the correct thing to do. |