在“if”语句中有多个布尔条件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在“if”语句中有多个布尔条件?相关的知识,希望对你有一定的参考价值。
我正在尝试用多个布尔条件编写一个“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”。我该如何解决?
答案
使用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块。
另一答案
使用
true
代替
if
以下代码说明......
if (result)
以上是关于在“if”语句中有多个布尔条件?的主要内容,如果未能解决你的问题,请参考以下文章