• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the best to use String and Boolean in If statement?  RSS feed

 
Ranch Hand
Posts: 31
Android Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

At the moment I'm having trouble with a small project that I'm doing. I want to write a program that ask if you want to go to the movies. If the user type in yes then it'll print out (Alright let go) but if the user type no then it would print (whatever). The trouble that I'm having is. What's the best way to use Boolean and Strings together in a if statement? Is there something I miss? (I'm still kinda new with all this)



Thank you for your help
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, comparing strings with == does not work. What this does is check if the two variables you are comparing refer to the exact same String object - it does not compare the content of strings. If you have two String objects with the same content, then comparing them with == will return false. Use equals() instead to compare strings by content.

What you are doing with all those variables and Boolean.toString(...) is much more complicated than necessary.

You can do the same thing like this:

Note that your code (and mine) does not check if the user entered "yes". It checks if the user entered "true". That is because the line yes = Boolean.toString(user1); will assign the string "true" to the variable yes.
 
Phillip Larson
Ranch Hand
Posts: 31
Android Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow Thank you so much for the fast reply, I understand it very clear now
 
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better choice of variable names would make the program read more naturally:

Note the little trick on line 6. Since the String literal "yes" is a String object, you can invoke methods on it. This technique helps you avoid a NullPointerException if answer happens to be null. Using equalsIgnoreCase() instead of just equals() makes the logic work irrespective of the whether the user types in "Yes", "YES", "yES" or any other combination of uppercase/lowercase letters on the console.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!