CMPS 134 Fall 2019
Sample Solutions for quiz of Nov. 18

1. Given was a Java method whose body is an if-else statement each branch of which includes a nested if-else statement. The method does nothing but print a sequence of strings (that happen to refer to characters from Star Trek). Exactly which strings are printed depends upon the value of the int parameter received by the method. The task was to show the output produced by each of three calls to the method, with a different actual parameter being passed to it each time.

(a) Sulu Scott
(b) Gorn Spock McCoy
(c) Sulu Scott


2. Given was a TossableCoin class and a client program that repeatedly tosses a pair of coins (i.e., instances of the TossableCoin class) until both coins are showing the same face. The task was to develop an alternative client program that tosses a single coin until two consecutive tosses resulted in Tails.

public static void main(String[] args) {
   TossableCoin coin = new TossableCoin();
   coin.toss();
   char prevResult;  // result of previous toss
   do {
      prevResult = coin.faceShowing();
      coin.toss();
   }
   while (!(coin.faceShowing() == 'T' && 
            prevResult == 'T'));

   System.out.println(coin.tossCount());
}
public static void main(String[] args) {
   TossableCoin coin = new TossableCoin();
   coin.toss();
   char prevResult = coin.faceShowing();
   coin.toss();
   while (!(coin.faceShowing() == 'T' &&
            prevResult == 'T')) {
      prevResult = coin.faceShowing();
      coin.toss();
   }
   System.out.println(coin.tossCount());
}
Solution using
a do-while loop
Solution using
a while loop