Skip to content

Instantly share code, notes, and snippets.

@jimmy087
Created May 4, 2013 05:59
Show Gist options
  • Save jimmy087/5516401 to your computer and use it in GitHub Desktop.
Save jimmy087/5516401 to your computer and use it in GitHub Desktop.
Count number of appearance of a digit in a string.
public class Exercise9_5 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter a string: ");
String s1 = input.nextLine();
int [] counts = countDigits(s1);
// Display results.
for (int i = 0; i < counts.length; i++) {
if (counts [i] > 0) {
System.out.println((char)(1 + i) + " appears " + counts[i] + ((counts[i] == 1) ? " time." : " times."));
}
}
}
public static int[] countDigits(String s1) {
// TODO Auto-generated method stub
int [] counts = new int [10];
for (int i = 0; i < counts.length; i++) {
if (Character.isDigit(s1.charAt(i))) {
counts [s1.charAt(i) - 1]++;
}
}
return counts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment