我想要完成的是以下...... 询问用户号码并检查用户输入提供的号码是否为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;
}
答案 0 :(得分:6)
有效的电话号码不一定是整数(例如,包含国家/地区代码的+
符号)。所以请改用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));
}
}
答案 1 :(得分:0)
以下是您最初想法的实例。
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;
}