A set of code has already instantiated c to be a Coin and has input a String guess, from the user asking whether the user guesses that a coin flip will result in “Heads” or “Tails”. Which of the following sets of code will perform the coin flip and see if the user’s guess was right or wrong?
a) c.flip( );
if(c.isHeads( ).equals(guess)) System.out.println("User is correct");
b) if(c.flip( ).equals(guess)) System.out.println("User is correct");
c) if(c.isHeads( ).equals(guess)) System.out.println("User is correct");
Lewis/Loftus/Cocking: Chapter 4 Test Bank TB 39
d) c.flip( );
if(c.toString( ).equals(guess)) System.out.println("User is correct");
e) c.flip( ).toString( );
if(c.equals(guess)) System.out.println("User is correct");
Answer: d. Explanation: c.flip( ) must be performed first to get a Coin flip. Next, the user’s guess is compared against the value of the Coin’s flip. The Coin c stores the result as an int and the user’s guess is a String. Using getFace( ) returns the int value but using the toString method will return the String “Heads” or “Tails”. So, the code compares c.toString( ) with the user’s guess using the String method equals.