-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuessTheNumber.java
More file actions
77 lines (64 loc) · 1.87 KB
/
GuessTheNumber.java
File metadata and controls
77 lines (64 loc) · 1.87 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
import java.util.Scanner; // input package
import java.util.Random; // for generating random number
// RUNNING VERSION
class Game
{
private int num, guess, noOfGuesses;
Scanner obj = new Scanner(System.in); // for entering number
public Game() // default constructor for random number
{ // value setting
Random ran = new Random();
num = ran.nextInt(101); // 0 to 100
}
public void takeUserInput() // for taking input
{
do // input with validation
{
System.out.print(" Enter a number between 0 to 100 : ");
guess = obj.nextInt();
} while (guess < 0 || guess > 100);
}
public boolean isCorrectNumber()
{
boolean check = false;
if (guess == num)
{
noOfGuesses++;
check = true;
}
else if (guess > num)
{
noOfGuesses++;
System.out.println(" Try Lower : ");
}
else
{
noOfGuesses++;
System.out.println(" Try Higher : ");
}
return check; // when number is found
}
public void setNoOfGuesses() {
noOfGuesses = 0; // assign a value of 0 for default
}
public int getNoOfGuesses()
{
return noOfGuesses;
}
}
public class GuessTheNumber // MAIN CLASS
{
public static void main(String[] args)
{
boolean b; // checking value
Game dani = new Game(); // random number generated as well
dani.setNoOfGuesses(); // setting default value
do // validation here as well
{
dani.takeUserInput();
b = dani.isCorrectNumber(); // assigning boolean value using return statement
} while(!b);
// OUTPUT OF getting correct number
System.out.println(" You got your Number Correct! in " + dani.getNoOfGuesses() + " Guesses ! ");
}
}