[英]Validating 7 digit phone number
我要完成的工作如下:向用戶詢問數字,並檢查用戶輸入提供的數字是否為7位整數。 如果是字符串,則拋出InputMismatchException並再次詢問數字。 除了使用正則表達式並提供數字1234567之外,還有其他簡便的方法嗎? 另一個問題是,如果我輸入一個值,例如12345678,則由於int會四舍五入,因此如何避免這種情況。
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}
有效的電話號碼不一定是整數(例如,包含國家代碼的+
號)。 因此,請使用字符串代替。
基本正則表達式(7位數字,不驗證國家/地區代碼等)的簡單示例:
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}
這是與您的原始想法類似的有效示例。
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.