Programming Practice: Loops


More robust user input

Consider the partially-completed getYesNoAnswer method below.  The method prompts the user to enter a yes (1) or no (0) answer.  If the user does not enter a 1 or 0, the user is repeatedly prompted to re-enter an answer.  Once the user has entered an appropriate value, the user's response is converted to a boolean response (and returned).

/**
 * Prompts the user for a yes or no answer.
 * @param in the Scanner for user input
 * @return the answer (true for yes, false for no)
 */
public static boolean getYesNoAnswer(Scanner in) {
    // METHOD BODY
}
Complete the body of the method:

using a while loop

 

 

 

 

 

 

using a do-while loop

 

 

 

 

 

 


Product of odds

Write a code fragment that computes the product of the first M odd (positive) numbers.  For example, if M is 4, the code fragment should compute 1 x 3 x 5 x 7.

 

 

 

 

 

 

 


Fibonacci sequence

The Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, ...  The first and second Fibonacci numbers are 1; to figure out the next Fibonacci number, you take the sum of the previous two Fibonacci numbers (e.g., the next number in the sequence shown is 8 + 13 = 21).  Write a code fragment that prints out the first 100 Fibonacci numbers.