在“if”语句中有多个布尔条件?

问题描述 投票:0回答:2

我正在尝试用多个布尔条件编写一个“if”语句。现在,我有5个不同的布尔变量。在“if”语句中,我想根据布尔变量为true来打印不同的东西。我现在拥有的代码打印出每个“if”语句的结果,而不是仅显示真实的结果。

boolean result = Arrays.equals(user, Jamie); //compares the arrays
boolean result2 = Arrays.equals(user, David);
boolean result3 = Arrays.equals(user, Sally);
boolean result4 = Arrays.equals(user, Susan);
boolean result5 = Arrays.equals(user, Mary);

if (result = true) {
        Address a = new Address (20, 201107, "Pizza", "blue"); //makes the different objects
        printLines (a); //calls the printLines method to print out the "Secret information" about the user
} 
if (result2 = true) {
        Address b = new Address (56, 211045, "Noodles", "Pink");
        printLines (b);
}
if (result3 = true) {
        Address c = new Address (46, 329432, "Hamburgers", "Green");
        printLines (c); 
}
if (result4 = true) {
        Address d = new Address (80, 322810, "Fried Rice", "Yellow");
        printLines (d);
}
if (result5 = true) {
        Address e = new Address (35, 405029, "Steak", "Red");
        printLines (e);
}
else {
        System.out.println ("Password is wrong");
}

基本上,我想要程序做的只是当“结果”为真时打印对象“a”。但是,现在,当“结果”为真时,程序会打印所有对象(a,b,c,d和e),而不是仅打印“a”。我该如何解决?

if-statement boolean
2个回答
0
投票

使用else if确保只评估一个闭包:

if (result) {
    Address a = new Address (20, 201107, "Pizza", "blue"); //makes the different objects
    printLines (a); //calls the printLines method to print out the "Secret information" about the user
} 
else if (result2) {
    Address b = new Address (56, 211045, "Noodles", "Pink");
    printLines (b);
}
else if (result3) {
    Address c = new Address (46, 329432, "Hamburgers", "Green");
    printLines (c); 
}
else if (result4) {
    Address d = new Address (80, 322810, "Fried Rice", "Yellow");
    printLines (d);
}
else if (result5) {
    Address e = new Address (35, 405029, "Steak", "Red");
    printLines (e);
}
else {
    System.out.println ("Password is wrong");
}

正如您的代码目前所代表的那样,如果多个结果布尔变量是qazxsw poi,那么可能会评估多个qazxsw poi块。


0
投票

使用

true

代替

if

以下代码说明......

if (result)
© www.soinside.com 2019 - 2024. All rights reserved.