if (menuNumber = 1)
should be
if (menuNumber == 1)
The former assigns the value 1 to menuNumber
, the latter tests if menuNumber
is equal to 1.
The reason you get cannot convert an int to boolean
is that Java expects a boolean in the if(...)
construct - but menuNumber
is an int
. The expression menuNumber == 1
returns a boolean, which is what is needed.
It's a common mix-up in various languages. I think you can set the Java compiler to warn you of other likely cases of this error.
A trick used in some languages is to do the comparison the other way round: (1 == menuNumber)
so that if you accidentally type =
you will get a compiler error rather than a silent bug.
This is known as a Yoda Condition.
In Java, a similar trick can be used if you are comparing objects using the .equals()
method (not ==
), and one of them could be null:
if(myString.equals("abc"))
may produce a NullPointerException
if myString
is null. But:
if("abc".equals(myString))
will cope, and will just return false
if myString
is null.