-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursionGuessNumberGameCode
More file actions
49 lines (40 loc) · 1.85 KB
/
Copy pathRecursionGuessNumberGameCode
File metadata and controls
49 lines (40 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*Doug Bennett */
/*12/05/2017 */
/*This program is a guessing game designed to demonstrate */
/*how recursive programming works */
/************************************************************/
import java.util.Scanner;
public class RecursionGuessNumberGame {
public static void guessNumber(int lowNum, int highNum) {
Scanner scnr = new Scanner(System.in);
int midNum = 0; // Midpoint of low and high number
char userAnswer = '-'; // User guess
midNum = (highNum + lowNum) / 2;
// Asks user for input
System.out.print("Is it " + midNum + "? (l/h/y): ");
userAnswer = scnr.next().charAt(0);
if ((userAnswer != 'l') && (userAnswer != 'h')) { // Base case: found number
System.out.println("Thank you!");
}
else { // Recursive case: split into lower OR upper half
if (userAnswer == 'l') { // Guess in lower half
guessNumber(lowNum, midNum); // Recursive call
}
else { // Guess in upper half
guessNumber(midNum + 1, highNum); // Recursive call
}
}
return;
}
public static void main(String[] args) {
// Print game objective, user input commands
System.out.println("Choose a number from 0 to 100.");
System.out.println("Answer with:");
System.out.println(" l (your num is lower)");
System.out.println(" h (your num is higher)");
System.out.println(" any other key (guess is right).");
// Call recursive function to guess number
guessNumber(0, 100);
return;
}
}