繁体   English   中英

使用chararray的字符串索引超出范围异常

[英]String index out of bounds exception using chararray

以下代码应将电话号码字符转换为实际的电话号码整数。 例如800-NEXT-DAY = 800-639-8329。 但是,无论我进入result.substring索引是什么,我都会使字符串索引超出范围部分,我也不知道为什么。 试图找出解决方法。

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

您的for循环结尾处的半冒号结束了您的for循环。 您不想结束for循环。 结束for循环不允许result用switch语句更新,导致在调用result.substringresult仍然是" " 更改; {

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

同时在末尾添加一个} 这解决了您遇到的索引超出范围的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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