teaching machines

CS 145 Lab 6 – Logical operators and conditionals

March 7, 2012 by . Filed under cs145, labs, spring 2012.

Prelab

Logical operators

In lecture we’ve explored the logical operators &&, ||, and !. These operators are as important to a programmer as a screwdriver and hammer are to a mechanic. Do whatever you can to learn their use.

Suppose you have the following variables are at your disposal, all describing some individual person:

Checkpoint #1: craft expressions using the variables above for the following derived attributes of this person. Do not write if statements; write only boolean expressions.

  1. A person is eligible for benefits if he/she works half-time (20 hours) or more on average each week.
    boolean isBenefitsEligible =
  2. A person is a teenager if he/she is between 13 and 19 years old, inclusively.
    boolean isTeenager =
  3. A person is a bachelor if he is an unmarried man.
    boolean isBachelor =
  4. A person is busy if he/she has children or typically works over 45 hours a week on average.
    boolean isBusy =
  5. See the variable name.
    boolean notBornInOctober1990 =
  6. A person goes to Starbucks if he/she earns over $30,000 or drinks coffee.
    boolean goesToStarbucks = 
  7. A person can have children if he is male. A female can also have children if she is less than 45 years old and does not drink coffee.
    boolean canHaveChildren =

Conditionals

Though boolean expressions are interesting and useful in and of themselves, they are almost always used as gatekeepers for loops (which execute 0 or more times) and conditional statements (which execute 0 times or 1 time). Solve one of the following problems, both of which require some conditional gatekeeping.

  1. Roll a 6-sided die some large number of times. (At least 100000. Make the number easily variable.) Determine the die’s fairness by reporting how many 1s were rolled, how many 2s, 3s, 4s, and so on.
  2. Write a method named getOrdinal that takes in an int parameter and returns a String in which the parameter is followed by its correct ordinal suffix: “st”, “nd”, “rd”, or “th”.

Checkpoint #2: show your instructor or TA your working code and output.

TODO

  1. Complete homework 2.