Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java programming question?
Wondering if anyone can help...trying to add a boolean method to my program.
Basically, if someone takes a box from a shelf, the method returns true while the method for being on the shelf changes to false. if the box is not on the shelf, then takebox returns false.
However, i can only get this to return false for both for some reason.
public boolean takeBox()
{
if(isOnShelf == true)
return true && (isOnShelf = false);
else {
if (isOnShelf == false);
return false;
}
I'm a complete newbie but this has had me scratching my head for an hour now.... any tips?
Thank you both. That makes total sense...I was definitely confusing it for doing two things. It works perfectly, but more importantly, the concept makes sense, and I'm gonna need that about five more times for this project, so I'm glad you explained it so thoroughly.
2 Answers
- McFateLv 710 years agoFavorite Answer
In Java, "&&" isn't like Perl where it means "do this AND that" -- it's a boolean operator that only evaluates to true if both sides evaluate to true.
The value of an assignment statement (e.g., "x=3") is the value assigned in the statement. Since isOnShelf happens to be boolean, the value of that assignment ("isOnShelf = false") is "false". Which means that your return statement boils down to "return true && false" which will return false.
In general, you can use booleans directly without bothering to compare them to true/false. (e.g. "if (x)" is preferred to "if (x == true)", and "if (! x)" is preferred to "if (x == false)".
Personally, I would write your method as:
==========
public boolean takeBox() {
if (isOnShelf) {
isOnShelf = false;
return true;
} else {
return false;
}
}
==========
- 10 years ago
public boolean takeBox()
{
if(isOnShelf == true) {
isOnShelf = false;
return true;
}
return false;
}
Basically, what is happening is it is evaluating the statement "return true && (isOnShelf = false);" as false because "isOnShelf = false" is evaluating to false.
Also, you do not need the else statement in there. If isOnShelf is true, then it will never reach the second return statement, so you don't need to worry about any other condition.
e: Haha, it seems I always have a top contributor beat me. Oh well.