forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoreScanner.java
More file actions
48 lines (40 loc) · 1.12 KB
/
Copy pathMoreScanner.java
File metadata and controls
48 lines (40 loc) · 1.12 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
import java.util.Scanner;
public class MoreScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int max = 5;
int input = readInt(scanner, max);
if(input == -1){
System.out.println("User input was invalid!");
}
else{
System.out.println("User typed " + input);
}
input = readIntWhile(scanner, max);
System.out.println("User typed " + input);
scanner.close();
}
public static int readInt(Scanner sc, int max){
System.out.print("Enter an integer between 1 and " + max + ": ");
int digit = -1;
if(sc.hasNextInt()){
digit = sc.nextInt();
sc.nextLine(); // eat the rest of the line the user typed
}
if(digit < 1 || digit > max){
return -1;
}
return digit;
}
public static int readIntWhile(Scanner sc, int max){
int digit = -1;
while(digit < 1 || digit > max){
System.out.print("Enter an integer between 1 and " + max + ": ");
if(sc.hasNextInt()){
digit = sc.nextInt();
}
sc.nextLine(); // eat the rest of the line the user typed
}
return digit;
}
}