如何只允许整数且不允许超过9位数字

问题描述

        System.out.println("Enter your phone number: ");
    while(in.hasNextLong()) {
        long phone = in.nextLong();
        if(in.hasNextLong()) {
            if(phone < 1000000000) {
                System.out.println("Phone number: "+phone); 
        }
    } else if(!in.hasNextInt()) {
        System.out.println("Please enter a valid phone number: ");
    } else if (phone < 1000000000) {
        System.out.println("Please enter a valid phone number: ");
    }
    

尝试了另一种方式

        boolean valid;
    long phone;
    do {
        System.out.println("Enter your phone number: ");
        
        if(!in.hasNextLong()) {
            phone =in.nextLong();
            if(phone > 1000000000) {
            System.out.println("Please enter a valid phone number");
            in.nextLong();
            valid=false;
            }
        } 
        }while(valid=false);
    System.out.println("Phone: " + phone);

如您所见,它根本不起作用,特别是如果您输入了一个非整数并且要求输入两次,对不起,一团糟

edit:好的,有没有不用正则表达式的方法吗?我的讲师还没有教过,所以我不确定我是否允许使用正则表达式

解决方法

您需要使用正则表达式。看看 https://www.w3schools.com/java/java_regex.asp

然后尝试一些方法...

...
final boolean isValid = inputValue.match(^[0-9]{1,9}?) // 1 to 9 digits
if (isValid) {
  ...
}
...
,

我建议这样做:

System.out.println("Enter your phone number: ");
int phone;
for (;;) { // forever loop
    String line = in.nextLine();
    if (line.matches("[0-9]{1,9}")) {
        phone = Integer.parseInt(line);
        break;
    }
    System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: "+phone);
,

这是我不使用正则表达式的方法

System.out.println("Enter your phone number: ");
int phone;
int index = 0;
while(true) { 
    String line = in.nextLine();
    if (valid(line)){
        phone = Integer.parseInt(line);
        break;
    }
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: " + phone);

还有valid()方法

boolean valid(String line){
    if(line.length() > 9) return false;
    for(int i = 0; i < line.length(); i++){
       boolean isValid = false;
       for(int asciiCode = 48; asciiCode <= 57 && !isValid; asciiCode++){
       //48 is the numerical representation of the character 0
       // ...
       //57 is the numerical representation of the character 9 
       //see ASCII table
          if((int)line.charAt(i) == asciiCode){
             isValid = true;
          }
       }
       if(!isValid) return false;
    }
    return true;
}