我试图编写一个 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/