Created
May 4, 2013 05:59
-
-
Save jimmy087/5516401 to your computer and use it in GitHub Desktop.
Count number of appearance of a digit in a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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