I am having some trouble with writing a method that when prompted with a number returns how many times each value is repeated. For example, if the number 7846597 is entered the method would return:
0 - 0 1 - 0 2 - 0 3 - 0 4 - 1 5 - 1 6 - 1 7 - 2 8 - 1 9 - 1
I know this would be most easily done with a loop, but I am not sure how to write the actual code. I also know that I need to convert the number value I get as an input into a string so I can use char methods.
This is my attempt:
public double countOccurences(int num) { String str = num + ""; int goneThrough = 0; int count0 = 0; int count1 = 0; int count2 = 0; int count3 = 0; int count4 = 0; int count5 = 0; int count6 = 0; int count7 = 0; int count8 = 0; int count9 = 0; while(goneThrough <= str.length()) { int value = 0; if(value >= 10){ value = value * 0; } if(str.charAt(0) == 0) count0++; if(str.charAt(0) = 1) count1++; } return count0; return count1; return count2; return count3; return count4; return count5; return count6; return count7; return count8; return count9; }
Advertisement
Answer
countOccurences(int num)
should return the number of occurrences of each digit as int[10]
.
static int[] countOccurences(int num) { int[] result = new int[10]; for ( ; num > 0; num /= 10) ++result[num % 10]; return result; } public static void main(String[] args) { int input = 7846597; int[] output = countOccurences(input); for (int i = 0; i < 10; ++i) System.out.println(i + " - " + output[i]); }
output:
0 - 0 1 - 0 2 - 0 3 - 0 4 - 1 5 - 1 6 - 1 7 - 2 8 - 1 9 - 1