I am trying to create a method that will count the number of occurrences of digits in a string and record them into an array.
For example if the string entered into the method is “1223000”, then counter[1] =1, counter[2] =2, counter[3] = 1, counter[0] = 3.
I keep getting a arrayindexoutofbounds error, here is the code I have soo far:
//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;
}
See my comment for how to correct the issue.
You should also consider looping the characters of the string directly, rather than tracking the position in the string and using
charAt.For example,
Testing the above using the below code results in no error (
java -ea DigitFreqTest).Note the above does not support Unicode… in that case, you may wish to instead use
Character.getNumericValue.Note I had to improvise using a
Map<Integer, Integer>because Java does not inherently provide a multiset collection 🙁