-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighLow.java
More file actions
77 lines (69 loc) · 2.45 KB
/
Copy pathHighLow.java
File metadata and controls
77 lines (69 loc) · 2.45 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;
public class HighLow {
public static int numberOfGuesses;
public static int gameNumber;
public static void main(String[] args) {
initGame();
}
public static void initGame() {
boolean programRunning;
boolean gameRunning = true;
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the High / Low Guessing Game!");
do {
gameNumber = randomWithRange(1, 100);
System.out.println("The random number is: " + gameNumber);
do {
gameRunning = runRound(sc);
} while (gameRunning);
programRunning = getYesOrNo(sc).equals("y");
} while (programRunning);
System.out.println("Good bye!");
}
public static boolean runRound(Scanner sc) {
boolean gameNotWon = false;
System.out.print("Please enter a guess: ");
int playerGuess = getInteger(1, 100, sc);
if (playerGuess == gameNumber) {
System.out.println("GOOD GUESS!");
gameNotWon = false;
} else if (playerGuess > gameNumber) {
System.out.println("LOWER");
numberOfGuesses++;
gameNotWon = true;
System.out.println("Number of guesses made: " + numberOfGuesses);
} else {
System.out.println("HIGHER");
gameNotWon = true;
numberOfGuesses++;
System.out.println("Number of guesses made: " + numberOfGuesses);
}
return gameNotWon;
}
public static int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
public static int getInteger(int min, int max, Scanner sc) {
if (!sc.hasNextInt()) {
System.out.println("Not a number!");
return getInteger(min, max, sc);
}
int userInput = sc.nextInt();
if (userInput >= min && userInput <= max) {
return userInput;
} else {
System.out.println("Number not in range!");
return getInteger(min, max, sc);
}
}
public static String getYesOrNo(Scanner sc) {
String userChoice;
do {
System.out.println("Do you wish to play again? [y/n]: ");
userChoice = sc.next().trim();
} while (!userChoice.equalsIgnoreCase("y") && !userChoice.equalsIgnoreCase("n"));
return userChoice;
}
}