0

Got my program done and this is the only piece I cant figure out I have to check to see if the user entered String userPhone is an integer

System.out.println("Please enter your phone number (10-dights only)");
        String userNumber=sc.nextLine();

        while(true) {
            if (userNumber.length()==10) {
                order01.cust1.setPhoneNumber(userNumber);
                break;
            }
            else if (userNumber.length()!=10) {
                System.out.println("Invalid phone number, Enter a valid one");
            }
            userNumber=sc.nextLine();
        }   
  • 1
    You might want to take a look at https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation?noredirect=1&lq=1 in case you are specifically looking to match phone number patterns. – Naman Oct 27 '17 at 04:05

4 Answers4

0

You could use a regular expression to validate that the String contains exactly ten digits that would be \d{10} - and you don't need an else after your break. Like,

while(true) {
     if (userNumber.matches("\\d{10}")) {
         order01.cust1.setPhoneNumber(userNumber);
         break;
     }
     System.out.println("Invalid phone number, Enter a valid one");
     userNumber=sc.nextLine();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

check matching for digits. matches() method of string take regular expression. Here \d* represent all characters should be digits only. and before that we are checking for length also.

 while(true) {
        if (userNumber.length()==10 && userNumber.matches("\\d*")) {
            System.out.println(userNumber);
            break;
        }
        else if (userNumber.length()!=10 || !userNumber.matches("\\d*")) {
            System.out.println("Invalid phone number, Enter a valid one");
        }
        userNumber=sc.nextLine();
    }
Devram Kandhare
  • 771
  • 2
  • 8
  • 20
0

The easiest and most primitive would be to loop through the input string(since your string is only 10 units long) and check if character at each index is a digit using Character.isDigit

hsnsd
  • 1,728
  • 12
  • 30
0

Please refer for the link for more information and original credits to this link : Original Code

Try the below method:

       public static boolean isNumber(String string) {
        try {
            Long.parseLong(string);
        } catch (Exception e) {
            return false;
        }
        return true;
        }

in your code :

if (isNumber(userPhone)) {
         order01.cust1.setPhoneNumber(userNumber);
         break;
     }
Karan
  • 695
  • 1
  • 6
  • 16