编写复杂的Java布尔表达式



我正在尝试编写一个代码,如果满足以下条件,它会说嫁给我,否则它会说迷路。

需要满足的条件:

22至27岁男性,不吸烟,身高72英寸以下,体重160磅以下,长相好看,能够搬迁。">

这是我迄今为止编写的代码。然而,即使我相信它符合给定的标准,它的打印也会丢失?怎么了?

此外,我怎么能用一个布尔值来表示它呢?

public class marry {
    public static void main(String[] args) {
        int weight = 150;
        int age = 24;
        int height = 71;
        boolean isASmoker = false;
        boolean isMale = true;
        boolean isGoodLooking = true;
        boolean isAbleToRelocate = true;
        if (((weight < 160 && (age <= 27 && age >= 22)) && ((height < 72) && ((isASmoker = false) && (isMale = true))) && ((isGoodLooking = true) && (isAbleToRelocate = true)))) {
            System.out.println("Marry Me!");
        }
        else {
            System.out.println("Get Lost!");
        }
    }
}

感谢

您的布尔表达式不正确。单个"="执行赋值。您需要"=="进行布尔比较。

更改

isASmoker = false

isASmoker == false

isMale = true

isMale == true

至于可读性,可以通过删除不必要的括号并将(variable==false(更改为!变量这在某种程度上是一个偏好问题,尽管我想大多数人都会同意,正如所写的那样,这个表达很长,很难理解。

试试我的小代码来决定你的问题:

class Person {
    private int weight;
    private int age;
    private int height;
    private boolean isASmoker;
    private boolean isMale;
    private boolean isGoodLooking;
    private boolean isAbleToRelocate;
    public Person(int weight, int age, int height, boolean isASmoker, boolean isMale, boolean isGoodLooking, boolean isAbleToRelocate) {
        this.weight = weight;
        this.age = age;
        this.height = height;
        this.isASmoker = isASmoker;
        this.isMale = isMale;
        this.isGoodLooking = isGoodLooking;
        this.isAbleToRelocate = isAbleToRelocate;
    }
    public boolean isGood() {
        return weight < 160 && age <= 27 && age >= 22 && 
               height < 72 && !isASmoker && isMale && 
               isGoodLooking && isAbleToRelocate;
               // (variable == true) => variable
               // (variable == false) => !variable
    }
    public static void main(String[] args) {
        Person person = new Person(150, 24, 71, false, true, true, true);
        System.out.println(person.isGood() ? "Marry Me!" : "Get Lost!");
    }
}
 public class marry {
    public static void main(String [] args) {
               int weight = 150;
               int age = 24;
              int height = 71;
              boolean isASmoker = false;
              boolean isMale = true;
              boolean isGoodLooking = true;
              boolean isAbleToRelocate = true;
        if ( ( ( weight < 160 && ( age <= 27 && age >= 22 ) ) && ( ( height < 72 ) && ( ( isASmoker == false ) && ( isMale) ) ) && ( ( isGoodLooking ) && ( isAbleToRelocate ) ) ) ) {
           System.out.println("Marry Me!");
        } else {
           System.out.println("Get Lost!");
        }
   }
}

试着这样做,它可能会工作

如果您想检查布尔值是否为真,您甚至不必使用==运算符。您可以在if语句中对布尔值(例如isMale(进行右键操作。最初出错的地方是在if语句中使用=运算符而不是==运算符,但我为您清理了更多。

正如EJK所说的=是一个赋值运算符,但是在检查booleans时甚至不需要==,所以更新以匹配以下内容。

isASmoker = false!isASmoker

isMale = trueisMale

最新更新