简体   繁体   English

布尔值,if-else语句和扫描器?

[英]Booleans, if-else statements, and scanner?

I am trying to make the "yes" (or "y" in this case) response to a question a true statement. 我试图使对一个问题的“是”(或本例中的“ y”)回答为真实的陈述。 Any other response to the question below is known to be a false statement. 对以下问题的任何其他答复都被认为是错误的陈述。

System.out.print("Do you smoke?(y/n): ");
        boolean smoker = console.nextBoolean();
        if (smoker.equalsIgnoreCase("y")) {
            smoker = true;
        } else {
            smoker = false;
        }

I get the error 我得到错误

HealthPlan.java:32: error: boolean cannot be dereferenced
        if (smoker.equalsIgnoreCase("y")) {
              ^

Does anyone know how I can fix this? 有谁知道我该如何解决? I have searched this online and I am not so sure. 我已经在网上搜索过此信息,但不确定。

Can't cast a String to a boolean , catch the console.next line as a String . 无法将String转换为boolean ,将console.next行作为String捕获。 Check if it's y and then place the the value in a boolean 检查是否为y,然后将值放入布尔值

String smoker = console.nextLine();
boolean isSmoker = false;
if (smoker.equalsIgnoreCase("y")) {
    isSmoker = true;
}

You have two problems here. 您在这里有两个问题。

First your variable smoker is of type boolean . 首先,您的可变smokerboolean类型。 Which is a primitive type. 这是原始类型。 A primitive type is not an object, you can't call a method or an attribute on it. 基本类型不是对象,不能在其上调用方法或属性。 So you can't write smoker.someAttribute or smoking.someMethod() . 因此,您不能编写smoker.someAttributesmoker.someAttribute smoking.someMethod() This is why you get this Exception. 这就是为什么您得到此异常的原因。

Second, your variable is of type boolean so you can only affect boolean to it. 其次,您的变量的类型为boolean因此您只能对其影响布尔值。 But you are trying to affect a String to it, it will obviously fail. 但是,您尝试对其影响字符串,则它显然会失败。 This error is hidden cause of the first one. 此错误是第一个错误的隐藏原因。


The solution is the same for both problem. 对于两个问题,解决方案都是相同的。 Either check directly the console input, or pass it to a String variable then check this variable value. 直接检查控制台输入,或将其传递给String变量,然后检查此变量值。 Then after the check, affect the correct boolean value to smoker . 然后在检查之后,将正确的布尔值影响到smoker

With the direct check : 直接检查:

boolean smoker = false;
if(console.nextLine().equalsIgnoreCase("y")){
    smoker = true;
}

With a String variable 带字符串变量

boolean smoker = false;
String consoleInput = console.nextLine();
if(consoleInput.equalsIgnoreCase("y")){
    smoker = true;
}

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

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