-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExcp2.java
48 lines (41 loc) · 1.19 KB
/
Excp2.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
/**
* iostream workshop code #2 - Exception Handling
* -> LBYL vs EAFP (InputMisMatchException0)
*/
import java.util.*;
class Main {
public static void main(String[] args) {
// int x = getIntLBYL();
int x = getIntEAFP();
System.out.println("x is: " + x);
}
private static int getInt () {
Scanner input = new Scanner (System.in);
System.out.print("Please enter an integer: ");
return input.nextInt();
}
private static int getIntLBYL () {
Scanner input = new Scanner (System.in);
boolean isValid = true;
System.out.print("Please enter an integer: ");
String n = input.next();
for (int i=0; i<n.length(); i++) {
if (!Character.isDigit (n.charAt(i))) {
isValid = false;
break;
}
}
if (isValid)
return Integer.parseInt(n);
return -1;
}
private static int getIntEAFP () {
Scanner input = new Scanner (System.in);
System.out.print("Enter an integer: ");
try {
return input.nextInt();
} catch (InputMismatchException e) {
return -1;
}
}
}