-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHighlow.java
81 lines (66 loc) · 3.13 KB
/
Highlow.java
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
import java.util.Scanner;
// you always want to import stuff at the top
// single line comment
// comments are ignored by the computer
/* (multi line comments)
-------- What we will be programming------
Main goal:
the user will guess a random number provided by the computer
the game will go on until the player is able to guess the number
------------------------
- the code will contain a scanner to get the user input
- a variable to store the guess
- a variable to create a random int
- while loop that will end when the user guesses the number
- multiple if statement to declare winner
*/
public class Highlow {
public static void main(String[] args) {
// Use Scanner for getting input from user
Scanner keyinput = new Scanner(System.in);
// keyinput is the name of the variable
// System.in allows your code to access the input
// Math.random() produces decimal value
int random = (int) (Math.random() * 100 + 1);
// (int) in here converts decimal value created by math.random to integer
int guess = -1;
// -1 is there just to make sure
// int can hold both negetive and positive number (there is a max and min value
// limit tho)
// loop that will run until the user has guessed the correct value
while (guess != random) {
// while [the user input](guess) is not equal to
// [random number generated by ] the computer run this code
// I will use try and catch method incase there is an error with the
// user input (Always have error handeling method)
try {
// try will tell the computer to run this code
// catch will be exected if there is any unexpected problems such as
// user putting letters instead of numbers
// user prompt
System.out.print("Enter your guess: ");
// get user input
guess = keyinput.nextInt();
// keyinput is the scanner
// next int is used when the users have to input whole numbers
// if statements
if (guess < random) {
// if the number guessed by the user is less than the number randomly generated
System.out.println("Number guessed is too low :(");
} else if (guess > random) {
// if the number is not low and
// but it is higher run this
System.out.println("Number guessed is too high :(");
} else {
// if the number is not high or low execute this
System.out.println("Correct, the number was " + random);
}
} catch (Exception e) {
// for now just think of Exception e as errors
System.out.println("There was an error please try again");
keyinput.next();
// we want to clean the input other wise there would be an infinite loop
}
}
}
}