Skip to content

Commit 88a387b

Browse files
Exercise 3 Solution
1 parent 0ee2506 commit 88a387b

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

50.Exercise_3_Solution/README.md

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Java Tutorial: Exercise 3 - Solutions & Shoutouts
2+
3+
#### Create a class Game, which allows a user to play "Guess the Number" game once.
4+
5+
- Game should have the following methods:
6+
- Constructor to generate the random number
7+
- takeUserInput() to take a user input of number
8+
- isCorrectNumber() to detect whether the number entered by the user is true
9+
- getter and setter for noOfGuesses
10+
11+
**Use properties such as noOfGuesses(int), etc to get this task done!**
12+
13+
```
14+
import java.util.Random;
15+
import java.util.Scanner;
16+
17+
class Game{
18+
public int number;
19+
public int inputNumber;
20+
public int noOfGuesses = 0;
21+
22+
public int getNoOfGuesses() {
23+
return noOfGuesses;
24+
}
25+
26+
public void setNoOfGuesses(int noOfGuesses) {
27+
this.noOfGuesses = noOfGuesses;
28+
}
29+
30+
Game(){
31+
Random rand = new Random();
32+
this.number = rand.nextInt(100);
33+
}
34+
void takeUserInput(){
35+
System.out.println("Guess the number");
36+
Scanner sc = new Scanner(System.in);
37+
inputNumber = sc.nextInt();
38+
}
39+
boolean isCorrectNumber(){
40+
noOfGuesses++;
41+
if (inputNumber==number){
42+
System.out.format("Yes you guessed it right, it was %d\nYou guessed it in %d attempts", number, noOfGuesses);
43+
return true;
44+
}
45+
else if(inputNumber<number){
46+
System.out.println("Too low...");
47+
}
48+
else if(inputNumber>number){
49+
System.out.println("Too high...");
50+
}
51+
return false;
52+
}
53+
54+
}
55+
public class cwh_50_ex3sol {
56+
public static void main(String[] args) {
57+
/*
58+
Create a class Game, which allows a user to play "Guess the Number"
59+
game once. Game should have the following methods:
60+
1. Constructor to generate the random number
61+
2. takeUserInput() to take a user input of number
62+
3. isCorrectNumber() to detect whether the number entered by the user is true
63+
4. getter and setter for noOfGuesses
64+
Use properties such as noOfGuesses(int), etc to get this task done!
65+
*/
66+
67+
Game g = new Game();
68+
boolean b= false;
69+
while(!b){
70+
g.takeUserInput();
71+
b = g.isCorrectNumber();
72+
}
73+
74+
}
75+
}
76+
```
77+
78+
**Ultimate Java Cheatsheet: [Click To Download](https://api.codewithharry.com/media/videoSeriesFiles/courseFiles/java-tutorials-for-beginners-50/UltimateJavaCheatSheet.pdf)**

0 commit comments

Comments
 (0)