-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathValidateInput.java
More file actions
30 lines (28 loc) · 971 Bytes
/
Copy pathValidateInput.java
File metadata and controls
30 lines (28 loc) · 971 Bytes
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
import java.util.Scanner;
public class ValidateInput{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int lineNum = 0;
while(true){
System.out.printf("%nEnter the employee info: ");
String entry = scanner.nextLine();
System.out.println("nextline() value: " + entry); // for debug puporse
entry = entry.trim(); // remove the possible leading and trailing spaces.
if(entry.matches("(?i)quit")){ // Use embedded flag expression to ignore the case
break;
}
if(entry.matches("\\w+\\s+\\d+")){
// legal entry
String[] items = entry.split("\\s+");
System.out.printf("%1$d. Name: %2$s, Age: %3$s%n", ++lineNum, items[0], items[1]);
}else if(entry.matches("\\D+")){
System.out.println("age field missing.");
}else if(entry.matches("\\d+")){
System.out.println("name field missing.");
}else{
System.out.println("Violate format rule: name age");
}
}
scanner.close();
}
}