-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandomnumbergame.java
More file actions
52 lines (50 loc) · 1.66 KB
/
randomnumbergame.java
File metadata and controls
52 lines (50 loc) · 1.66 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
import java.util.Scanner;
import java.util.Random;
class numberGame
{
Random r=new Random();
Scanner sc=new Scanner(System.in);
int score=0;
int max_attempts=5;
void playGame()
{
boolean playAgain;
do{
int random_number=r.nextInt(100)+1;
int attempts_left=max_attempts;
boolean isCorrect=false;
System.out.println("A random number between 1 and 100 has been generated. Guess it!");
while(attempts_left>0)
{
System.out.print("Enter your guess: ");
int guess=sc.nextInt();
attempts_left--;
if(guess==random_number)
{
System.out.println("Congratulations! Your guess is correct.");
score++;
isCorrect=true;
break;
}
else if(guess>random_number)
System.out.println("Your guess is too high! ");
else
System.out.println("Your guess is too low!");
System.out.println("Attempts left: "+attempts_left);
}
if(!isCorrect)
System.out.println("Out of attempts! The correct number was: "+random_number);
System.out.print("Do you want to play this game again? (Yes/No): ");
playAgain=sc.next().equalsIgnoreCase("Yes");
}while(playAgain);
System.out.println("Game Over. Your final score is: "+score);
}
}
class randomnumbergame
{
public static void main(String args[])
{
numberGame obj=new numberGame();
obj.playGame();
}
}