即使索引在数组长度内,也会出现数组索引越界错误

rat*_*erd 2 java arrays indexing char indexoutofboundsexception

我试图编写一个java程序,其中输入整数的每个数字都以单词形式打印。

例如:输入 123应该产生输出 "one two three"

我编写了以下程序,它接受一个整数值,然后将其转换为字符串。然后,我迭代字符串的字符并将它们转换为整数值,稍后将其用作数组的索引。

但我得到了ArrayIndexOutOfBoundsException

Index 49 out of bounds for length 10
Run Code Online (Sandbox Code Playgroud)

我的代码:

public class DigitsAsWords {
    static void Print_Digits(int N){
        String arr[] = {"zero","one", "two", "three", "four","five", "six", "seven", "eight", "nine"};
        String st = Integer.toString(N);
        System.out.println(st);
        char s;
        int a;
        for (int i=0; i<st.length(); i++){
            s = st.charAt(i);
            a = Integer.valueOf(s);
            System.out.print(arr[a]+" ");
        }
    }
    public static void main (String args[]){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        Print_Digits(a);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*ala 6

这是您的代码失败的地方:

a = Integer.valueOf(s);
Run Code Online (Sandbox Code Playgroud)

它没有转换'1'1您所期望的,而是转换'1'为等效的 ASCII 码 49。

为了避免这种情况:

a = Character.getNumericValue(s);
Run Code Online (Sandbox Code Playgroud)

这将转换'1'1, 等等。