1.挑战要求
编写一个程序,提示输入名字、姓氏、邮编和工号。规则如下:
- 必须填写名字
- 必须填写姓氏
- 名字和姓氏至少2个字符长
- 工号必须是 “AA-1234”这样的格式,即两个字母,一个连字符,四个数字
- 邮编必须是数字
2.java程序
import java.util.Scanner;
import java.util.regex.Pattern;
public class CheckInput {
public static void main(String[] args) {
// TODO Auto-generated method stub
String firstName = "";
String lastName = "";
String zipCode = "";
String employeeID = "";
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first name:");
// get the first name
do {
// use hasNextLine() instead of hasNext()
// if you enter nothing ,hasNextLine() can get the enter
if (scanner.hasNextLine()) {
firstName = scanner.nextLine();
break;
}
} while (true);
System.out.print("Enter the last name:");
// get the last name
do {
if (scanner.hasNextLine()) {
lastName = scanner.nextLine();
break;
}
} while (true);
System.out.print("Enter the ZIP code:");
// get the ZIP code
do {
if (scanner.hasNextLine()) {
zipCode = scanner.nextLine();
break;
}
} while (true);
System.out.print("Enter an employee ID:");
// get the employee ID
do {
if (scanner.hasNextLine()) {
employeeID = scanner.nextLine();
break;
}
} while (true);
scanner.close();
boolean noProblem = true;
// check first name
int len = checkLength(firstName);
if (len == 0) {
System.out.println("The first name must be filled in.");
noProblem = false;
} else if (len < 2) {
System.out.println("\"" + firstName + "\" is not a valid first name.It's too short.");
noProblem = false;
}
// check last name
len = checkLength(lastName);
if (len == 0) {
System.out.println("The last name must be filled in.");
noProblem = false;
} else if (len < 2) {
System.out.println("\"" + lastName + "\" is not a valid last name.It's too short.");
noProblem = false;
}
// check ZIP code
boolean isZIPRight = checkZIP(zipCode);
if (!isZIPRight) {
System.out.println("The ZIP code must be numeric.");
noProblem = false;
}
// check employee ID
boolean isIdRight = CheckID(employeeID);
if (!isIdRight) {
System.out.println(employeeID + " is not a valid ID.");
noProblem = false;
}
if (noProblem) {
System.out.println("There were no errors found.");
}
}
// return length
private static int checkLength(String value) {
// TODO Auto-generated method stub
return value.length();
}
private static boolean checkZIP(String input) {
// TODO Auto-generated method stub
String zipPattern = "^[0-9]{1,}$";
return Pattern.matches(zipPattern, input);
}
private static boolean CheckID(String value) {
// TODO Auto-generated method stub
String idPattern = "^[a-z,A-Z]{2}-[0-9]{4}$";
return Pattern.matches(idPattern, value);
}
}