简体   繁体   中英

Int can't be converted into boolean

I needed to visualize a menu into the function menu and then use a switch to differentiate the cases, but there's a problem in the while condition where it says "int cannot be converted into boolean" even though the scelta variable and the type of return of the menu function are both int. Can anyone give me an help? I'm new to Java.

public class PComputer {
    
    public static void main(String[] args) 
    {
        int scelta;
      
        while(scelta=menu())
        {
          //code
        }
  
    }
    
    static int menu()
    {
        Scanner keyboard = new Scanner(System.in);
        
        int scelta;
        
        do
        {
            System.out.println("************************************************************");
            System.out.println("ACCESSO AL MENU DI SISTEMA-SELEZIONARE L'AZIONE VOLUTA: ");
            System.out.println("1- Creazione e inserimento dati studente: ");
            System.out.println("2- Creazione e inserimento dati computer: ");
            System.out.println("3- Aggiugni computer: ");
            System.out.println("4- Elimina computer: ");
            System.out.println("5- Ricerca per codice: ");
            System.out.println("6- Ricerca computer acquistati dopo una certa data: ");
            System.out.println("7- Ricerca computer con una certa caratteristica: ");
            System.out.println("8- Elenco studenti a cui è stato assegnato un pc: ");
            System.out.println("0- Esci");
            System.out.println("************************************************************");
            scelta=keyboard.nextInt();    
            
            if(scelta<0 || scelta>9)
            {
                System.out.println("Si prega di inserire un numero valido!");
            }
        }
        while(scelta>0 || scelta<9);
        
        return scelta;
    } 
}

There are 2 different interpretations of what this code intended to mean. There's the obvious one when looking at just the code, but your text around the snippet suggests the other one.

It feels like person A wrote this code, gave to you, and now you're asking questions about it. In which case, you've misunderstood what's happening in that while loop rather thoroughly.

In any case, either interpretation requires a code update; as is, the code doesn't work as you figured out (it does not compile).

Interpretation 1: Truthy/falsy

The main method code is supposed to work as follows:

Ask the user which option they want, and store the result in scelta . Forget the while loop for a moment, to that just once you would write:

scelta = menu();

That's java-ese for: Run the menu method, then assign what it returns to the scelta variable.

In addition, the main method would like to do that not just once, it would like to do this repeatedly, until the user picks choice 0.

Now you need to know 2 things in order to understand why in almost all programming environments, the code as written would accomplish this precise thing. It just doesn't work in java. Which is why I think this is what the original author intended.

  • assignments are themselves expressions. Just like 5 + 5 is 10, and menu() resolves to whatever option the user chooses, a = 5 assigns the value of 5 to a but it is itself also an expression with value 5. int b = (a = 5) + 20 is valid java (and valid in many other languages), and means a is 5, and b ends up being 20. Thus, scelta = menu() is not just 'ask the user for the menu', but also 'and then assign that value to scelta , and it even does a third thing: That whole expression is also the value chosen.
  • Just about every expression, boolean or not, is legal inside a while loop ( but not in java!! ), and a somewhat complex list of rules dictates whether the value will be considered 'true' or 'false'.

Obviously the boolean value true is considered true, but in many languages, a string is considered true if it is not empty and false if it is empty, and a number is considered true if it isn't 0, and false if it is 0. This is called truthy/falsy: For example, in javascript, 0 is falsy and 1 is truthy. You can try this in your browser (open the dev console) right now:

var a = 1;
if (a) console.log("Whoa");

copy/paste that in, and 'Whoa' appears, because javascript considers the value of a (which is 1 here), truthy.

Combine those 2 factors and voila: This code would do exactly what you want (ask for the menu, repeatedly, and have the variable scelta contain the choice, and have the while loop abort when the user chooses 0 , the only falsy number on the list), and all in a tiny line, just while (scelta = menu()) .

But java does not work that way.

In java, true is true, false is false, and all other values are neither truthy nor falsy: They are just compiler errors.

truthy/falsy is convenient but too easily misunderstood and has too many hard to answer questions. Is the string "false" true or false? Is the string " " (note the spaces) true or false? In bash, 0 is truthy and non-zero is falsy, in all other truthy/falsy languages, it's the other way around. Given that = is assignment, if java was truthy/falsy, typoing a == into a single = would not be a compiler error (you WANT typos to be a compiler error, so that's bad), and so on. So java just doesn't 'do' truthy/falsy, and in my opinion, this is superior language design.

Fortunately, it's easy to make this loop do what you want in java as well: All you need is to explicitly say that you want 0 to be considered false:

while ((scelta = menu()) != 0) {
 ...
}

Interpretation 2: You meant comparison

Your question included the text:

variable and the type of return of the menu function are both int. Can anyone give me an help

It sounds like you think this code is intended to compare scelta and menu(), and loop as long as they are equal.

But this interpretation makes not one iota of sense. scelta does not have a value yet, so even if you turn that into == (in java, = is assignment, and == is 'are they equal?) the code would still fail to compile with a different error (trying to read scelta before assigning a value to it). But just looking at this code, that entire concept makes no sense. What point is there in having a variable containing a choice and then showing the user a menu, and then looping for as long as they pick the same choice as you pre-picked for them?

At any rate, if this somehow is what you desired, Just make that == , that fixes the current problem you have, but then you'll run into the next problem (code can have more than 1 error in it, of course).

But I doubt it. Reread interpretation 1, that's what you want here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM