-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGame.java
More file actions
83 lines (69 loc) · 2.43 KB
/
NumberGame.java
File metadata and controls
83 lines (69 loc) · 2.43 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// TASK 1
import java.util.Scanner;
import java.util.Random;
public class NumberGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rd = new Random();
// generate random number between in the given range
int lowerBound = 1;
int upperBound = 100;
// to keep the random number in range
int randomNumber = rd.nextInt(upperBound - lowerBound + 1) + lowerBound;
int attempts = 0;
// limiting the number of attempts
int maxAttempts = 4;
boolean correctGuess = false;
System.out.println("Guess the number between "+ lowerBound + " and "+ upperBound+".");
System.out.println("you have "+maxAttempts+" attempts to guess!");
while(attempts < maxAttempts)
{
System.out.println("Enter your guess: ");
int userGuess = sc.nextInt();
attempts++;
if(userGuess < randomNumber)
{
if(attempts < maxAttempts)
{
System.out.println("To low! Try again.");
}
}
else if(userGuess > randomNumber)
{
if(attempts < maxAttempts)
{
System.out.println("To high! Try again.");
}
}
// when userGuess = randomNumber
else
{
System.out.println("Congratulations! You guessed the correct number in "+ attempts +" attempts");
correctGuess = true;
break;
}
if(attempts < maxAttempts)
{
System.out.println("You have "+ (maxAttempts - attempts) + " attempts left.");
}
}
// when attempts exceeds maxAttempts
if(!correctGuess)
{
System.out.println("Sorry,You have used all the attempts. Correct number was "+ randomNumber + ".");
}
System.out.println("Do you want to play again ? (yes or no): " );
// clear the buffer
sc.nextLine();
String playAgain = sc.nextLine();
if(playAgain.equalsIgnoreCase("yes"))
{
// restart the game
main(new String[]{});
}
else
{
System.out.println("Thankyou for playing !");
}
}
}