relyt relyt - 2 months ago 8
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.

Uri Uri
Answer

Your first problem is with the use of the Java scanner. If I am not mistaken, you are only reading the first substring up to the first space. You probably wanted to run over the entire string, so a scanner is not the right thing to use.

Once you get the entire string, you still have a problem. The major problem in your code is that in the line that reads

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

you have a semicolon at the end. As a result of this, the next line (where you update the values) is always executed. This is a problem because sometimes your character would not be a digit, so the index "character-'0'" could fall outside the 10 that you have defined. This should be caught by Java to create an exception. You're not seeing this exception because your code would only process the first "23"