Booleans and selection
Java for AP CS A Lesson 3 1:55 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A relational operator compares two values and produces a boolean — true or false.
关系运算符比较两个值,产生一个布尔值——true 或 false。
Score greater than fifty is true.
score > 50 是 true。
Score double-equals one hundred is false.
score == 100 是 false。
Score not-equals seventy-five is also false.
score != 75 也是 false。
And because that answer is a real value, you can store it in a variable of type boolean.
而因为这个答案是一个真实的值, 你可以把它存进一个 boolean 类型的变量里。
One warning: a double equals compares, while a single equals assigns.
一句提醒:双等号是比较,单个等号是赋值。
Selection in Java puts the condition in round brackets and the block in braces.
Java 里的选择结构,把条件放在圆括号里,把代码块放在花括号里。
Follow n equals minus four down the chain.
跟着 n = -4 沿这条链走一遍。
First test: minus four is not greater than zero, so move on.
第一个测试:-4 不大于 0,往下走。
Second: is it less than zero?
第二个:它小于 0 吗?
Yes, so negative prints.
是,于是打印 negative。
And the else is never reached, because the chain stops at the first test that passes.
而那个 else 从来没被问到, 因为链条在第一个通过的测试处就停住了。
Now the AP-specific idea.
现在说 AP 专门要考的那一点。
Double ampersand is and, double bar is or, and an exclamation mark is not.
双与号是 and,双竖线是 or,感叹号是 not。
But and does something you cannot see in a listing.
但 and 做了一件你在代码清单里看不出来的事。
Look: if the left side is false, Java already knows the whole thing is false, so it never even runs the right side.
看:如果左边是 false, Java 已经知道整个表达式必然是 false, 于是它"根本不会去跑"右边。
Here that means calling length on something that might be nothing never happens — and that is exactly what stops the crash.
在这里,这意味着"对一个可能是空的东西调用 length()"这件事压根没发生—— 而这正是崩溃被挡住的原因。
Four things to take with you.
带走四点。
One: a comparison gives a boolean you can store.
第一:比较给出一个你可以存起来的布尔值。
Two: an else if is only reached when the ones above failed.
第二:只有上面那些都不成立时,才会走到 else if。
Three: double ampersand is and, double bar is or, bang is not.
第三:双与号是 and,双竖线是 or,感叹号是 not。
Four: and short-circuits — a false left side skips the right.
第四:and 会短路——左边为假就跳过右边。
Now write some conditions in the tasks below.
现在去下面的题里写几个条件。