In this section, we'll extend our code with "boolean logic" .. using andornot to combine multiple true/false tests.
Boolean Logic: && || !
Want to be able to combine tests, in English like this:
- Name starts with "A" and ends with "y"
In code this is boolean logic (George Boole)
and&& (two ampersands)
or|| (two vertical bars)
not! (exclamation mark, holding off on this one for now)
Sorry the syntax is a bit cryptic -- historical syntax accident
Boolean Logic Example 1
table3-1
The && joins a startsWith test and an endsWith test
The whole test is written on two lines because it is kind of long (optional)
Standalone rule: -The tests joined by && || must be syntactically complete tests on their own
-The tests are then joined with && or ||
-Outer set of parenthesis around the whole thing
Common error 1: row.getField("name).startsWith("A") && endsWith("y")
Common error 2:too few right parenthesis around the test
(demo) common errors, above + omitting the {, typing & instead of &&
Boolean Logic Example 2 (You Try It)
Change the code below so it prints rows where the following is true:
"Popular A Name:" Name starts with "A" and rank is <= 50
Notice: eyeball the answer to verify that it's reasonable
table3-2
If logic inside the loop:
if (row.getField("name").startsWith("A") &&
row.getField("rank") <= 50) {
print(row);
}
Boolean Logic Example 3
Now do an example with or || -- change the code below to print rows where the following is true:
Name starts with "X" or name starts with "Y" or name starts with "Z" (note: can hand-check the output after running)
table3-3
If logic inside the loop:
// your code here
if (row.getField("name").startsWith("X") ||
row.getField("name").startsWith("Y") ||
row.getField("name").startsWith("Z")) {
print(row);
}
Many Boolean Examples
Here is the working code for the "Popular A" names test mentioned above.
table3-4
Experiments to demo (then Students try 8 and later)
For these examples, we'll use one of && || but not both.
1. name starts with "Ab" or name starts with "Ac"
2. name starts with "Ab" or name starts with "Ac" or name starts with "Al"
3. name starts with "O" and name ends with "a"
4. name starts with "O" and gender is "girl"
5. name ends with "a" and gender is "boy"
6. rank is <= 10 and gender is "girl" (translation: "top 10 girl names")
7. rank is <= 10 or gender is "girl" (this one doesn't make a ton of sense, but what does this print?)
Students do these...
8. name ends with "ia" and gender is "boy" (hah, then try with gender is "girl")
9. name ends with "io" and gender is "girl" (then try "boy")
10. name ends with "o" and gender is boy and rank is >= 900
Experiment solution code:
If logic inside the loop:
// 1
if (row.getField("name").startsWith("Ab") ||
row.getField("name").startsWith("Ac")) {
print(row);
}