Repository navigation
Expand file tree
/
Copy pathGuessRecursive.java
More file actions
41 lines (35 loc) · 1.59 KB
/
Copy pathGuessRecursive.java
File metadata and controls
41 lines (35 loc) · 1.59 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
import java.util.Random;
import java.util.Scanner;
/**
* Guess My Number game with recursive method to guide user to the correct number.
*/
public class GuessRecursive{
public static void checkNum(int userNum, int myNum){ //checks if userNum is too high/low
if (myNum > userNum) {
System.out.println("Too low!");
userNum = getNum(); //if too low, prompts user for another number
checkNum(userNum, myNum); //and then checks that number
} else if (myNum < userNum) {
System.out.println("Too high!");
userNum = getNum(); //if too high, same as above
checkNum(userNum, myNum);
} else {
System.out.println("You got it!"); //if user is correct, program ends
}
}
public static int getNum() { //gets user input
int userNum;
Scanner in = new Scanner(System.in);
System.out.print("Type a number: ");
userNum = in.nextInt();
return userNum;
}
public static void main(String[] args) {
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("(including both). Can you guess what it is?");
int userNum = getNum();
Random random = new Random(); //chooses random number from 1-99
int myNum = random.nextInt(100) + 1;
checkNum(userNum, myNum);
}
}