[Java] (beginner) Is there a way to convert void (an object's state) to boolean?
if (ship1.contains(point)){ //points is the mouse location
ship1.show();
points= points +500;}
}
Right now the code will show ship1, a hidden object, if you click on it and add 500 "points". So if you click on ship1 again, it will remain seen and another 500 "points" will be added. Is there a way to restrict the code so that the 500 "points" will only be added if ship1 is hidden? I was thinking of adding an if statement, but I don't know how to say a hidden object = true. Also
.show()
is part of the library I used called objectdraw.
Posted Jul 22, 2015, 11:26 PM UTC
If your
ship1object has some kind of method that indicates if it is shown/hidden, you could use that. It looks like drawable objects in the "objectdraw" library have anisHidden()method, so it might look like:Thanks, that solved the problem. Out of curiosity, is there a method like
for converting between void and boolean?
Void is 'nothing'. You can't convert 'nothing' to anything. Your thinking about this the wrong way; methods return 'nothing' for a reason. If you just called "show" the object will be visible so there is no point if returning that state. If you wanted to check if the object is visible you would simply use a method (like isVisible()) to ask for it's state before setting it to the new state.
voidis not really a data type (like int, double, etc). It is the absence of a data type. It can't be converted to another type.In method declarations, the "void" keyword is used as a kind of placeholder when a method does not return a value. For example, look at this simple addition method:
This method takes in two integer parameters, adds them, and returns the sum. You would use the method like this:
Note that the value returned by the add() method is being assigned to a variable.
Now consider a different method that doesn't have any "return" value:
This method's return type is
void. It doesn't return anything; so you can't assign its return value to a variable, or use it in any other way.Fyi void is not a thing, void means a method returns nothing
What do you think void means? There is a specific Java meaning to void. I think you are confusing "hidden" with "void". They aren't the same.
You could write a helper method that checks for null and returns Boolean
Converting variable types can have unexpected consequences, you may not know how other parts of the code use that variable.
It's simply not possible.