0

I keep getting StringIndexOutOfBoundsException for this part of the code. What could be the reason? contact is declared as String

    do{

        System.out.print("Contact Number (01X-XXXXXXX) :");
        contact = scan.next();
        if(!phNumValidation(contact)){
            System.out.println("Invalid Phone Number. Please try again.");
            System.out.println("");
        }
    }while(!phNumValidation(contact) || contact.length() < 11);

this is the method for phone number validation

public static boolean phNumValidation(String contact){
    boolean valid = true;
    String dash = contact.substring(3, 4);
    if(contact.length() == 11){
        valid = true;
        valid = contact.startsWith("01");
        valid = dash.matches("-");
    }
    else{
        valid = false;
    }

    return valid;
}
Jason Hew
  • 13
  • 4

3 Answers3

0

move the contact.length<11 validation on the left-side of the or (talking about the while statement).

Otherwise you are entering into the phNumValidation even with less than 11chars contacts. And that method is not prepared for that.

albert_nil
  • 1,648
  • 7
  • 9
0

You get the exception because you tend to pass contact of length <=4 to phNumValidation function and do a substring without checking the length first. Below code will not throw any exception as length would be checked first. While loop would also need not call the function again.

  boolean valid = false;
  do{
        System.out.print("Contact Number (01X-XXXXXXX) :");
        contact = scan.next();
        if(!phNumValidation(contact)){
            System.out.println("Invalid Phone Number. Please try again.");
            System.out.println("");
        }else{
            valid = true;
        }


    }while(!valid);


public static boolean phNumValidation(String contact){
    boolean valid = true;

    if(contact.length() == 11){
    String dash = contact.substring(3, 4);
    valid = true;
        valid = contact.startsWith("01");
        valid = dash.matches("-");
    }
    else{
        valid = false;
    }

    return valid;
}
Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
0

It's time for you to use regular expressions, for example this is how my validation method would look like.

public static boolean phNumValidation(String contact){
    return contact.matches("01\\d-\\d{7}");
}

This method validates length, format all at once.

QuakeCore
  • 1,886
  • 2
  • 15
  • 33