getOddInteger

Category: Programming
Author: Marty Stepp and Ruth Anderson
Book Chapter: 5.4
Problem: getOddInteger
Write a static method named getOddInteger that accepts as its parameter a Scanner for the console and repeatedly prompts the user until an odd integer (an integer not evenly divisible by 2) is entered, then returns this integer. If the user enters an integer that is even, or a token that is not an integer, an error message is displayed and the user is prompted again. You may assume that the user will type a single token as their response each time.

For example, the following log of execution represents the output from one call to your method. (User input is underlined.) After this output, the method returns 17, because this is the first odd integer typed by the user.

Type an odd integer: hello
Invalid input, try again.
Type an odd integer: okay
Invalid input, try again.
Type an odd integer: 268
Invalid input, try again.
Type an odd integer: 1.875
Invalid input, try again.
Type an odd integer: -24
Invalid input, try again.
Type an odd integer: 17

The following is another example log of execution in which the user types an odd integer on the first try. After this output, the method returns 285.

Type an odd integer: 285