Skip to content

Commit f0562ad

Browse files
committed
Greatest Number Game
1 parent db82406 commit f0562ad

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

ch07/GreatestNumber.java

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import java.util.Random;
2+
import java.util.Scanner;
3+
4+
public class GreatestNumber
5+
{
6+
public static void main(String[] args)
7+
{
8+
Scanner input = new Scanner(System.in);
9+
10+
System.out.print("Please Enter Your Name: ");
11+
String yourName = input.next();
12+
13+
int numberOfGuesses;
14+
numberOfGuesses = guessNumber();
15+
16+
17+
System.out.println("Congrats, " + yourName + "!!!");
18+
19+
playAgain();
20+
21+
}
22+
23+
public static int guessNumber()
24+
{
25+
Random randomNumber = new Random();
26+
Scanner input = new Scanner(System.in);
27+
28+
System.out.print("Please Guess A Number: ");
29+
int yourGuess = input.nextInt();
30+
31+
int random = randomNumber.nextInt(100) + 1;
32+
int guesses = 0;
33+
34+
while (random != yourGuess)
35+
{
36+
37+
if (yourGuess > random)
38+
{
39+
System.out.println("You are high");
40+
}
41+
else if (yourGuess < random)
42+
{
43+
System.out.println("You are low");
44+
}
45+
46+
System.out.print("Please Guess Again: ");
47+
yourGuess = input.nextInt();
48+
guesses++;
49+
50+
}
51+
if (random == yourGuess)
52+
{
53+
System.out.println("You are correct");
54+
guesses++;
55+
}
56+
57+
System.out.println("You guessed " + guesses + " times!");
58+
59+
return guesses;
60+
}
61+
62+
public static void playAgain()
63+
{
64+
Scanner input = new Scanner(System.in);
65+
66+
System.out.println("Do you want to play again? Type 'yes' or 'no'.");
67+
String playAgainAnswer = input.next();
68+
69+
int gamesPlayed = 1;
70+
71+
while (playAgainAnswer.equals("yes"))
72+
{
73+
74+
guessNumber();
75+
System.out.println("Do you want to play again? Type 'yes' or 'no'.");
76+
playAgainAnswer = input.next();
77+
gamesPlayed++;
78+
}
79+
80+
System.out.println("You played " + gamesPlayed + " games");
81+
82+
}
83+
84+
}

0 commit comments

Comments
 (0)