java - 数组索引越界错误,即使索引在数组长度内

标签 java arrays indexing char indexoutofboundsexception

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

例如:输入 123 应该产生一个输出 “一二三”

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

但是我得到了 ArrayIndexOutOfBoundsException

Index 49 out of bounds for length 10

我的代码:

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

最佳答案

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

a = Integer.valueOf(s);

它没有像您期望的那样将 '1' 转换为 1,而是将 '1' 转换为等效的 ascii 码 49。

为了避免这种情况:

a = Character.getNumericValue(s);

这会将 '1' 转换为 1,依此类推。

关于java - 数组索引越界错误,即使索引在数组长度内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72798014/

相关文章:

java - 是否保证所有 Java SE 1.5+ VM 都支持 MacRoman 编码?

javascript - 对项目数组(具有 X/Y 属性)进行排序,使它们从左到右、从上到下排序

python - 如何确定将哪些列设置为 Pandas DataFrame 中的索引?

Java 线程 - 两个 while 循环

java - 用于 Java 中的 Twitter 客户端的漂亮 GUI

java - 在 Hudson 上使用 Clover <fileset>

java - 在java中获取链表中的对象与数组中的对象

arrays - 深度复制数组,其中元素是自定义类的可选

c++ - 如何从文件重建 BST

indexing - iTunes 商店 : App keyword search optimization. 字符串智能索引?