简体   繁体   中英

String index out of bounds exception using chararray

the following code is supposed to convert phone number characters into the actual phone number integers. for example, 800-NEXT-DAY = 800-639-8329. But no matter what I enter into the result.substring index, I get the string index out of range section and i don't know why. Trying to figure out how to fix it.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String result = " ";
    System.out.print("Enter a phone number");
    String initialNumber = input.nextLine();

    for(char c: initialNumber.toLowerCase().toCharArray());
    switch(c){
    case '0':                                         result+="0";
    case '1':                                         result+="1";break;
    case '2': case 'a': case 'b': case 'c':           result+="2";break;
    case '3': case 'd': case 'e': case 'f':           result+="3";break;
    case '4': case 'g': case 'h': case 'i':           result+="4";break;
    case '5': case 'j': case 'k': case 'l':           result+="5";break;
    case '6': case 'm': case 'n': case 'o':           result+="6";break;
    case '7': case 'p': case 'q': case 'r': case 's': result+="7";break;
    case '8': case 't': case 'u': case 'v':           result+="8";break; 
    case '9': case 'w': case 'x': case 'y': case 'z': result+="9";break;
    }
    String s1 = result.substring(0, 3);
    String s2 = result.substring(3, 6);
    String s3 = result.substring(6, 9);

    System.out.print(s1+s2+s3);
}}

Your semi colon at the end of your for loop ends your for loop. You do not want to end the for loop. Ending the for loop does not allow result to get updated with your switch statement causing result to still be " " when calling result.substring . Change your ; to a { .

for(char c: initialNumber.toLowerCase().toCharArray()){
    switch(c){
    case '0':                                         result+="0";
    case '1':                                         result+="1";break;
    case '2': case 'a': case 'b': case 'c':           result+="2";break;
    case '3': case 'd': case 'e': case 'f':           result+="3";break;
    case '4': case 'g': case 'h': case 'i':           result+="4";break;
    case '5': case 'j': case 'k': case 'l':           result+="5";break;
    case '6': case 'm': case 'n': case 'o':           result+="6";break;
    case '7': case 'p': case 'q': case 'r': case 's': result+="7";break;
    case '8': case 't': case 'u': case 'v':           result+="8";break; 
    case '9': case 'w': case 'x': case 'y': case 'z': result+="9";break;
    }
}

Also add a } to the end. This solves the index out of bounds issue you are encountering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM