relyt - 1 year ago 107
Java Question

# Find number of occurences of each digit in string

FYI. Another practice exercise that I'm stuck on. The problem is to find the number of occurences of each digit in a string. I feel like I'm pretty close, but I'm getting some whacky results. I'm a beginner, so please keep hints/help at my level if possible. Thanks!

Here is what I have so far:

``````import java.util.Scanner;

public class Practice5 {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter a string");
String s = input.next();

int[] counts = countNumbers(s);

String output = "";

for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
{
output += "Digit" + (char)('0' + i) + " appears " +
counts[i] + ((counts[i] == 1) + " times\n");
}

}

System.out.print(output);
}

private static int[] countNumbers(String s) {
int[] counts = new int[10];

for(int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i)));
counts[s.charAt(i) - '0']++;
}
return counts;
}
}
``````

Ok. Now if I enter a string like "23 t5t6 u76u 232 g1"

I get:

``````2 appears 1 time
3 appears 1 time
``````

This is obviously incorrect. It should be 2 appears 3 times, 3 occurs 2 times, 5 occurs 1 time, etc. Any help would be appreciated.

``````if (Character.isDigit(s.charAt(i)));