forked from PrajaktaSathe/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessTheNumber.java
More file actions
107 lines (95 loc) · 3.28 KB
/
GuessTheNumber.java
File metadata and controls
107 lines (95 loc) · 3.28 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.company;
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
int index = 0;
int rng = 20;
private int guesses = 10;
private int warning = 4;
private int guessedNo;
private int[] alreadyTold = new int[10];
private int specialWarning = 1;
public static void main(String[] args) {
GuessTheNumber n = new GuessTheNumber();
System.out.println(n.generateRand(20));
n.play();
}
public Scanner inputInt() {
System.out.print("\nEnter Your Guess: ");
return new Scanner(System.in);
}
public boolean isValid(Scanner inp) {
return inp.hasNextInt();
}
public int generateRand(int range) {
Random rand = new Random();
return rand.nextInt(range);
}
public void setAlreadyTold(int guess) {
this.alreadyTold[this.index] = guess;
this.index++;
}
public boolean isAlreadyTold(int guess) {
for (int i = 0; i < 10; i++) {
if (guess == this.alreadyTold[i]) {
return true;
}
}
return false;
}
public void printGuessed() {
for (int i = 0; i < 10; i++) {
if (alreadyTold[i] != -1) {
System.out.print(alreadyTold[i] + " ");
}
}
}
public void setGuessedToNull() {
for (int i = 0; i < 10; i++) {
alreadyTold[i] = -1;
}
}
public void play() {
setGuessedToNull();
int secretNum = generateRand(rng);
System.out.println("I am Thinking of a word between 0-" + rng + ".");
Scanner scanGuess;
int guess;
boolean flag = true;
do {
System.out.print("Remaining guesses: " + this.guesses + "\nRemaining warnings: " + this.warning + "\nGuessed Numbers: ");
printGuessed();
scanGuess = inputInt();
if (isValid(scanGuess)) {
guess = scanGuess.nextInt();
if (guess == secretNum) {
System.out.println("Congratulations! You have guessed the secret number!!");
flag = false;
} else if ((this.warning) > 0 && (this.guesses > 0)) {
if (isAlreadyTold(guess)) {
this.warning--;
this.guesses--;
System.out.println("You have already guessed this number");
} else if (guess < secretNum) {
this.guesses--;
System.out.println("Guessed number is less than secret number.");
setAlreadyTold(guess);
} else {
this.guesses--;
System.out.println("Guessed number is greater than secret number.");
setAlreadyTold(guess);
}
} else {
System.out.println("Game Over!");
flag = false;
}
} else if (this.specialWarning > 0) {
System.out.println("Invalid Input!!!");
this.specialWarning--;
} else {
System.out.println("Invalid Input!!!");
this.guesses--;
}
} while (flag);
}
}