-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidator.java
More file actions
89 lines (84 loc) · 2.82 KB
/
Validator.java
File metadata and controls
89 lines (84 loc) · 2.82 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
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Created by chand on 7/27/2017.
*/
import java.util.Scanner;
public class Validator {
public static String getString(Scanner sc, String prompt) {
System.out.print(prompt);
String s = sc.next(); // read user entry
sc.nextLine(); // discard any other data entered on the line
return s;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.println(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i < min)
System.out.println(
"Error! Number must be " + min + " or greater.");
else if (i > max)
System.out.println(
"Error! Number must be " + max + " or less.");
else
isValid = true;
}
return i;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(Scanner sc, String prompt,
double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d < min)
System.out.println(
"Error! Number must be " + min + " or greater.");
else if (d > max)
System.out.println(
"Error! Number must be " + max + " or less.");
else
isValid = true;
}
return d;
}
public static String yOrNValid(String yOrN) {
Scanner keyboard = new Scanner(System.in);
while (!yOrN.equalsIgnoreCase("y") && !yOrN.equalsIgnoreCase("n")) {
System.out.println("Invalid Input. Please enter Y or N: ");
yOrN = keyboard.nextLine();
}
return yOrN;
}
}