/*
Enter a string: jdk.8.0.40 and the big bang 3359421
0 appers 2 times.
1 appers 1 time.
2 appers 1 time.
3 appers 2 times.
4 appers 2 times.
5 appers 1 time.
8 appers 1 time.
9 appers 1 time.
*/
import java.util.Scanner;
public class CountNumberOccurs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = input.nextLine();
int[] counts = countsNumber(str);
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println(i + " appers " + counts[i] + ((counts[i] > 1) ? " times." : " time."));
}
}
public static int[] countsNumber(String str) {
int[] numbers = new int[10];
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i)))
numbers[str.charAt(i) - 48]++;
}
return numbers;
}
}
Introduction to Java Programming编程题9.5<统计字符串中数字的个数>
最新推荐文章于 2022-11-27 08:12:08 发布