【发布时间】:2026-02-05 07:40:01
【问题描述】:
我正在尝试创建一个方法来计算字符串中数字出现的次数并将它们记录到数组中。
例如如果输入方法的字符串是“1223000”,那么counter[1] =1,counter[2] =2,counter[3] = 1,counter[0] = 3。
我不断收到 arrayindexoutofbounds 错误,这是我到目前为止的代码:
//method: count number of occurences for digits
public static int[] count(String s){
int[] counter = new int[10];
for(int j= 0; j < s.length(); j++){
if (Character.isDigit(s.charAt(j)))
counter[s.charAt(j)] += 1;
}
return counter;
}
【问题讨论】:
-
需要从数字字符映射到数字;减去“0”。例如计数器[s.charAt(j) - '0']++;