Repository navigation
Expand file tree
/
Copy pathGuessMyNumber.java
More file actions
69 lines (55 loc) · 1.95 KB
/
Copy pathGuessMyNumber.java
File metadata and controls
69 lines (55 loc) · 1.95 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Scanner;
import java.util.Random;
public class GuessMyNumber {
public static void main(String[] args) {
// User attempts to guess a number randomized by program
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int replay, guess;
// Do while for replayability
do {
int remainingGuesses = 10, answer, min = 1, max = 100;
answer = rand.nextInt(max - min + 1) + min;
do {
System.out.print("Enter a number from 1 to 100: ");
guess = sc.nextInt();
remainingGuesses--;
if (guess >= 1 && guess <= 100) {
System.out.println("Guess: " + guess);
if (guess > answer) {
System.out.println("Too High");
System.out.println("Guesses Remaining: " + remainingGuesses);
if (remainingGuesses == 0) {
guess = answer;
System.out.println("Sorry, you are out of tries :(");
System.out.println("The number was " + answer);
break;
}
} else if (guess < answer) {
System.out.println("Too Low");
System.out.println("Guesses Remaining: " + remainingGuesses);
} else {
System.out.println("Correct! The number was " + answer);
System.out.println("It took you " + (10 - remainingGuesses) + " tries to get it!");
}
} else {
System.out.println("Guess: " + guess);
System.out.println("Invalid input. You still lose a try. Try again!");
System.out.println("Guesses Remaining: " + remainingGuesses);
}
} while (guess != answer);
System.out.println("Do you want to play again? ");
System.out.println("1 - Yes! Keep going.");
System.out.println("2 - No. Game over!");
replay = sc.nextInt();
if (replay == 1) {
continue;
} else if (replay == 2) {
System.out.println("Thanks for playing!");
} else {
System.out.println("Invalid input. Program ending...");
}
} while (replay == 1);
sc.close();
}
}