If an expression with integers

I am new to Java. I am looking for help with homework. I will not publish the complete code that I did initially, but I do not think that this will help me learn it.

I have a program that works with classes. I have a class that will test the selection and a class that has my setters and getters, and the class that the professor encoded using the program I / O (this is the book addres).

I have an expression in my main form that states

//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 the if if if (menuNumber = 1) , I get a red line that tells me that I cannot convert 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 this, so I wanted to ask for help. Do I need to convert my entry to a string? Now my validator looks something like this:

 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 int wont, should I change all this too?

Thanks again for helping me, I have not been so great, and I want to get a good piece of the job knocked out.

+4
source share
3 answers
 if (menuNumber = 1) 

it should be

 if (menuNumber == 1) 

The former sets the value to 1 menuNumber , the latter checks if menuNumber is 1.

The reason you get cannot convert an int to boolean is because Java expects a boolean in the if(...) construct, but menuNumber is int . The expression menuNumber == 1 returns a boolean that is necessary.

This is a common connection in different languages. I think you can configure the Java compiler to warn you of other probable cases of this error.


The trick used in some languages ​​is to make a comparison in the opposite direction: (1 == menuNumber) so that if you accidentally typed = , you get a compiler error, not a silent error.

This is called the State of Yoda .


In Java, you can use a similar trick if you are comparing objects using the .equals() method (not == ), and one of them may be null:

 if(myString.equals("abc")) 

may be NullPointerException if myString is null. But:

 if("abc".equals(myString)) 

will handle and just return false if myString is null.

+12
source

I get a red string that tells me that I cannot convert int to boolean.

This is because = is an assignment operator. You need to use the == operator.

+3
source

One equal sign is the assignment: you assign a value to a variable in this way. use two equal signs (==) to compare:

 if ($menuNumber = 1) { 

Update: forgotten dollar sign: $menuNumber

+2
source

Source: https://habr.com/ru/post/1398919/


All Articles