-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGuessTheNumber.java
67 lines (49 loc) · 1.86 KB
/
GuessTheNumber.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Scanner; // for reading user inputs
public class GuessTheNumber {
// function for number guessing game
public static void
guessTheNumberGame() {
// set the target number between 0 and 100
int target = (int)(100*Math.random());
System.out.println(target);
// prompt user to guess a number
System.out.println("Can you guess my number between 0 and 100 in 5 tries?");
int trials = 5;
// initialize scanner to read user input
Scanner reader = new Scanner(System.in);
for (int i = 0; i<trials;i++) {
// prompt user to guess a number
System.out.println("Enter a number: ");
// scan and store user input
int guess = reader.nextInt();
// if target number is correctly guessed
if (guess == target) {
System.out.println("Congrats! You guessed the number!");
break;
}
// if the target number is less than the guess
else if (guess > target) {
System.out.println("Try again! Hint: the number is less than " + guess);
}
// if the target number is greater than the guess
else if (guess < target) {
System.out.println("Try again! Hint: the number is greater than " + guess);
}
// if target number is correctly guessed
if (i == trials) {
System.out.println("Whoops! You ran out of tries! Better luck next time.");
break;
}
// //once finished
// reader.close();
System.out.println(guess);
}
}
// Driver Code
public static void
main(String arg[])
{
// Function Call
guessTheNumberGame();
}
}