-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomGuessNumber.java
58 lines (58 loc) · 2.1 KB
/
RandomGuessNumber.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
import java.util.Scanner;
import java.util.Random;
public class RandomGuessNumber{
private int lowerBound;
private int upperBound;
private int secretNumber;
private int maxAttempts;
private int score;
public RandomGuessNumber(int lowerBound,int upperBound,int maxAttempts){
this.lowerBound=lowerBound;
this.upperBound=upperBound;
this.maxAttempts=maxAttempts;
this.score=0;
}
public void PlayRound(){
Random random=new Random();
secretNumber=random.nextInt(upperBound-lowerBound+1)+lowerBound;
Scanner scanner=new Scanner(System.in);
System.out.println("Guess a Number between " +lowerBound +" and " +upperBound +".");
int attempts=0;
while(attempts<maxAttempts){
System.out.print("Enter Your Guess : ");
int guess=scanner.nextInt();
attempts++;
if(guess==secretNumber){
System.out.println("Congratulations! You have Guessed Correct Number ");
score+=maxAttempts-attempts+1;
break;
}
else if(guess<secretNumber){
System.out.println("Please Try Again! Your Number is Less than Guess");
}
else{
System.out.println("Please Try Again! Your Number is High than Guess");
}
}
if(attempts==maxAttempts){
System.out.println("Out of Attempts! Correct Number was " +secretNumber);
}
}
void Play(){
Scanner scanner=new Scanner(System.in);
boolean playAgain=true;
while(playAgain){
PlayRound();
System.out.println("Do ypou want to play again(Yes/No)?");
String choice=scanner.next();
if(!choice.equalsIgnoreCase("yes")){
playAgain=false;
}
}
System.out.println("Game Over! \nYour Total Score is : " +score);
}
public static void main(String[] args){
RandomGuessNumber game=new RandomGuessNumber(1,100,5);
game.Play();
}
}