我想要完成的是以下...询问用户的号码并检查用户输入提供的号码是否为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;
}
Run Code Online (Sandbox Code Playgroud)
有效的电话号码不一定是整数(例如,包含+国家/地区代码的符号).所以请改用String.
基本正则表达式的简单示例(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));
}
}
Run Code Online (Sandbox Code Playgroud)