简体   繁体   English

整数不能转换为布尔值

[英]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.我需要将菜单可视化到功能菜单中,然后使用开关来区分情况,但是在 while 条件中存在一个问题,即“int 无法转换为布尔值”,即使scelta变量和返回类型菜单功能都是int。 Can anyone give me an help?谁能给我一个帮助? I'm new to Java.我是 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.感觉就像是 A 人写了这段代码,给了你,现在你在问关于它的问题。 In which case, you've misunderstood what's happening in that while loop rather thoroughly.在这种情况下,您已经相当彻底地误解了 while 循环中发生的事情。

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解释1:真/假

The main method code is supposed to work as follows: main方法代码应该如下工作:

Ask the user which option they want, and store the result in scelta .询问用户他们想要哪个选项,并将结果存储在scelta Forget the while loop for a moment, to that just once you would write:暂时忘记 while 循环,只需一次你就可以这样写:

scelta = menu();

That's java-ese for: Run the menu method, then assign what it returns to the scelta variable.这就是 java-ese:运行菜单方法,然后将它返回的scelta分配给scelta变量。

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.此外, main方法不只是想这样做一次,它想重复这样做,直到用户选择选项 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.它只是在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.就像5 + 5是 10,并且menu()解析为用户选择的任何选项, a = 5a = 5的值赋给 a 但它本身也是一个值为 5 的表达式。 int b = (a = 5) + 20是有效的 java(在许多其他语言中也是有效的),意味着 a 是 5,而 b 最终是 20。因此, scelta = menu()不仅是“向用户询问菜单”,而且是“然后将该值分配给scelta ,它甚至做了第三件事:整个表达式也是选择的值。
  • 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'.几乎每个表达式,无论是否为布尔值,在 while 循环中都是合法的(但在 java 中不合法!! ),并且一个有点复杂的规则列表决定了该值是被视为“真”还是“假”。

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.显然布尔值true被认为是 true,但在许多语言中,如果字符串不为空则认为是 true,如果为空则认为是 false,如果数字不为 0 则认为是 true,如果为 0 则为 false . 这称为truthy/falsy:例如,在javascript 中, 0为falsy, 1为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.将其复制/粘贴进去,然后会出现“哇”,因为 javascript 会考虑 a 的值(此处为1 ),是真的。

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()) .结合这两个因素,瞧:此代码将完全按照您的要求执行(反复询问菜单,并让变量scelta包含选项,并在用户选择0时中止 while 循环,这是列表),并且所有内容都在一行中,就while (scelta = menu())

But java does not work that way.但是java不能那样工作。

In java, true is true, false is false, and all other values are neither truthy nor falsy: They are just compiler errors.在 java 中, true为 true, false为 false,所有其他值既不是 true 也不是 false:它们只是编译器错误。

truthy/falsy is convenient but too easily misunderstood and has too many hard to answer questions.真/假很方便,但太容易被误解并且有太多难以回答的问题。 Is the string "false" true or false?字符串“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.在 bash 中, 0为真,非零为假,在所有其他真/假语言中,情况正好相反。 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.鉴于=是赋值,如果 java 是真/假,将==输入单个=不会是编译器错误(您希望拼写错误是编译器错误,所以这很糟糕),依此类推。 So java just doesn't 'do' truthy/falsy, and in my opinion, this is superior language design.所以java只是不“做”真/假,在我看来,这是优秀的语言设计。

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:幸运的是,在 Java 中也很容易让这个循环做你想做的事情:你需要的只是明确说明你希望 0 被认为是假的:

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

Interpretation 2: You meant comparison解读2:你的意思是比较

Your question included the text:您的问题包括以下文字:

variable and the type of return of the menu function are both int.变量和菜单函数的返回类型都是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.听起来您认为此代码旨在比较scelta 和 menu(),并在它们相等时进行循环。

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). scelta还没有一个值,所以即使你把它变成== (在 Java 中, =是赋值,而==是'它们相等吗?)代码仍然会因为不同的错误而无法编译(试图读取scelta在为其分配值之前)。 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).无论如何,如果这正是您想要的,只需使==解决您当前遇到的问题,但随后您将遇到下一个问题(当然,代码中可能有 1 个以上的错误) .

But I doubt it.但我对此表示怀疑。 Reread interpretation 1, that's what you want here.重读解释1,这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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