Table-3 Boolean Logic

In this section, we'll extend our code with "boolean logic" .. using and or not to combine multiple true/false tests.

Boolean Logic: && || !

Boolean Logic Example 1


table3-1

 

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)

Experiment solution code:

If logic inside the loop:

  // 1
  if (row.getField("name").startsWith("Ab") ||
      row.getField("name").startsWith("Ac")) {
    print(row);
  }

  // 2
  if (row.getField("name").startsWith("Ab") ||
      row.getField("name").startsWith("Ac") ||
      row.getField("name").startsWith("Al")) {
    print(row);
  }

  // 3
  if (row.getField("name").startsWith("O") &&
      row.getField("name").endsWith("a")) {
    print(row);
  }

  // 4
  if (row.getField("name").startsWith("O") &&
      row.getField("gender") == "girl") {
    print(row);
  }

  // 5
  if (row.getField("rank") <= 10 &&
      row.getField("gender") == "girl") {
    print(row);
  }

  // 6
  if (row.getField("name").endsWith("ia") &&
      row.getField("gender") == "boy") {
    print(row);
  }

  // 7
  if (row.getField("rank") <= 10 ||
      row.getField("gender") == "girl") {
    print(row);
  }

  // 8
  if (row.getField("name").endsWith("ia") &&
      row.getField("gender") == "boy") {
    print(row);
  }

  // 9
  if (row.getField("name").endsWith("io") &&
      row.getField("gender") == "girl") {
    print(row);
  }

  // 10
  if (row.getField("name").endsWith("o") &&
      row.getField("gender") == "boy" &&
      row.getField("rank") >= 900) {
    print(row);
  }

> exercises