I’m new at Java. I’m looking for some help with homework. I wont post the full code I was doing that originally but I dont think it will help me learn it.
I have a program working with classes. I have a class that will validate a selection and a class that has my setters and getters and a class that the professor coded with the IO for the program (it’s an addres book)
I have a statement in my main like this that says
//create new scanner
Scanner ip = new Scanner(System.in);
System.out.println();
int menuNumber = Validator.getInt(ip, "Enter menu number: ", 1, 3);
if (menuNumber = 1)
{
//print address book
}
else if (menuNumber = 2)
{
// get input from user
}
else
{
Exit
}
If you look at my if statement if (menuNumber = 1) I get a red line that tells me I cannot convert an int to boolean. I thought the answer was if (menuNumber.equals(1)) but that also gave me a similar error.
I’m not 100% on what I can do to fix it so I wanted to ask for help. Do I need to convert my entry to a string? Right now my validator looks something like:
if (int < 1)
print "Error entry must be 1, 2 or 3)
else if (int > 3)
print "error entry must 1, 2, or 3)
else
print "invalid entry"
If I convert my main to a string instead of an int wont I have to change this all up as well?
Thanks again for helping me I haven’t been diong that great and I want to get a good chunk of the assignment knocked out.
should be
The former assigns the value 1 to
menuNumber, the latter tests ifmenuNumberis equal to 1.The reason you get
cannot convert an int to booleanis that Java expects a boolean in theif(...)construct – butmenuNumberis anint. The expressionmenuNumber == 1returns 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:may produce a
NullPointerExceptionifmyStringis null. But:will cope, and will just return
falseifmyStringis null.