You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数位转单词程序报ArrayIndexOutOfBoundsException异常

问题描述

需要实现Java程序功能:将输入整数的每一位数位转换为对应英文单词输出,例:输入123时,输出"one two three"。
原有实现逻辑:

  • 接收整数输入后先转换为字符串
  • 遍历字符串的每个字符将其转为整数值
  • 以转换得到的整数值为索引,访问存储了0-9对应英文单词的数组完成输出
    原以为使用的索引均在数组合法长度范围内,但程序运行时抛出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);
    }
}
错误原因

报错核心原因是字符转数值的逻辑错误:
直接对数字字符(比如'1')调用Integer.valueOf(s),得到的是该字符对应的ASCII编码值,不是字符代表的数位数值。数字0-9对应的字符'0'-'9'的ASCII值范围是48-57,比如字符'1'的ASCII值为49,正好对应报错里的非法索引49,而存储单词的数组长度为10,合法索引范围是0-9,自然会触发数组越界。
另外原代码缺少Scanner类的导入语句,本身就无法正常编译。

修复方法
  1. 修正字符转数位值的逻辑:数字字符的ASCII值是连续递增的,将拿到的字符减去'0'的ASCII值,就能得到对应的0-9整数值,即把a = Integer.valueOf(s);替换为a = s - '0';
  2. 在类定义前添加Scanner类的导入语句import java.util.Scanner;

修复后的完整可运行代码:

import java.util.Scanner;

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);
        char s;
        int a;
        for (int i=0; i<st.length(); i++){
            s = st.charAt(i);
            a = s - '0';
            System.out.print(arr[a]+" ");
        }
    }
    public static void main (String args[]){
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        Print_Digits(a);
    }
}

内容的提问来源于stack exchange,提问作者rat_basterd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 16:45:37