Jonathan2340
Jonathan2340

Reputation: 35

how to allow integer only AND not allowing more than 9 digits

        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: ");
    }
    

tried another way

        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);

as you can see it doesnt work at all especially if you input a non integer and it ask for input twice im sorry its a mess

edit: ok so is there a way without using regex? my lecturer hasnt taught it yet so im not sure im allowed to use regex

Upvotes: 0

Views: 811

Answers (3)

ABC
ABC

Reputation: 655

That's my approach without using regex

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);

And the valid() method

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;
}

Upvotes: 1

user3311510
user3311510

Reputation: 31

you need to use regex. take a look to https://www.w3schools.com/java/java_regex.asp

and try something along the lines...

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

Upvotes: 3

Andreas
Andreas

Reputation: 159114

I would recommend doing it this way:

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);

Upvotes: 1

Related Questions