您的位置:首页 > 编程语言 > Java开发

Introduction to Java Programming编程题9.5<统计字符串中数字的个数>

2015-08-24 23:55 656 查看
/*
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java