AP计算机教程4-2:复杂条件
当你希望两个条件同时为true时怎么办?可以使用逻辑与运算符&&来连接两个布尔表达式,这样仅当两表达式均为true时,最终的结果才为true。你妈妈可能会要求你在打扫房间和完成作业以后才能出门,以下是描述这种场景的代码。
public class Test1
{
public static void main(String[] args)
{
boolean cleanedRoom = true;
boolean didHomework = false;
if (cleanedRoom && didHomework) System.out.println("You can go out");
else System.out.println("No, you can't go out");
}
}
如果两条件成立一个即可呢?可以使用逻辑或运算符||来连接两个布尔表达式,这样只要其中一个为true最终的结果就会是true。爸爸说出门的话可以步行去或选择在他不用车时开家里的车,以下是描述这种场景的代码。
public class Test2
{
public static void main(String[] args)
{
boolean walking = true;
boolean carIsAvailable = false;
if (walking || carIsAvailable) System.out.println("You can go out");
else System.out.println("No, you can't go out");
}
}
被称为真值表(truth table)的下表展示了逻辑与和逻辑或的所有可能结果。
| P | Q | P && Q | P || Q |
| true | true | true | true |
| false | true | false | true |
| true | false | false | true |
| false | false | false | false |
0:00
What is printed when the following code executes and x has been set to 0?
if (x > 0 && (y / x) == 3) System.out.println("first case");
else System.out.println("second case");
x为0时x > 0为false,对于逻辑与而言程序将不执行第二个表达式而直接判定整个结果为false。What is printed when the following code executes and x has been set to 0?
if (x > 0 || (y / x) == 3) System.out.println("first case");
else System.out.println("second case");
false,还需判定第二个表达式的结果,在过程中会抛出除零的异常。&&和||均使用短路求解(short circuit evaluation),这意味着如果第一个条件已经能判断整个表达式的真假,就不用求解第二个条件了。对于逻辑与&&而言,如果第一个表达式为false,则整体必为false,不求解第二个条件。对于逻辑或||而言,如果第一个表达式为true,则整体必为true,不求解第二个条件。
What is printed when the following code executes and x has been set to 0 and y is set to 3?
if (x == 0 || (y / x) == 3) System.out.println("first case");
else System.out.println("second case");
x为0时x == 0为true,对于逻辑或而言程序将不执行第二个表达式而直接判定整个结果为true。What is printed when the following code executes and x has been set to -1?
String message = "help";
if (x >= 0 && message.substring(x).equals("help") System.out.println("first case");
else System.out.println("second case");
x为-1时x >= 0为false,对于逻辑与而言程序将不执行第二个表达式而直接判定整个结果为false。What is printed when the following code executes and x has been set to 0 and y is set to 3?
if ((y / x) == 3 || x == 0) System.out.println("first case");
else System.out.println("second case");
0 条评论