-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05HandsonActivity.java
54 lines (50 loc) · 2.06 KB
/
05HandsonActivity.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
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class ExceededLimitException extends Exception{
public ExceededLimitException(){
super("Number is out of range.");
}
}
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int input, attempt = 0, min, max;
min = 1;
max = 50;
int rng = ThreadLocalRandom.current().nextInt(min, max + 1);
do{
try {
System.out.println("Guess a number from 1 to 50!");
input = scan.nextInt();
if (input > rng && input < 50) {
System.out.println("Too high, try again.");
attempt++;
System.out.println("Correct Answer: (" + rng + ")");
System.out.println("Attempt(s): " + attempt);
} else if (input < rng) {
System.out.println("Too low, try again.");
attempt++;
System.out.println("Correct Answer: (" + rng + ")");
System.out.println("Attempt(s): " + attempt);
} else if (input > 50) {
throw new ExceededLimitException();
} else if (input == rng) {
attempt++;
System.out.println("You got it in " + attempt + " attempt(s)!");
break;
}
} catch (ExceededLimitException ele) {
System.out.println(ele.getMessage());
System.out.println("Correct Answer: (" + rng + ")");
System.out.println("Attempt(s): " + attempt);
continue;
} catch (InputMismatchException ime){
System.out.println("Invalid Input.");
System.out.println("Correct Answer: (" + rng + ")");
System.out.println("Attempt(s): " + attempt);
scan.next();
continue;
}
} while(true);
}
}