String类编程:给定一个由数字组成的字符串,统计每个数字出现的次数
今天看到了一个挺有意思的编程题,关于String类的API的使用,题目原题是这样的:给定一个由数字组成的字符串, 如:“1239586838923173478943890234092”;统计出每个数字出现的次数。
话不多说,直接上源码:
public class CountString {
public static void main(String[] args) {
String str = "1239586838923173478943890234092";
count(str);
}
public static void count(String string) {
int[] numbers = new int[string.length()];
int[] count = new int[10];
int a;
//将string分割为每个数字存储在numbers数组中
for (int i = 0; i < numbers.length; i++) {
//错误案例:numbers[i] = string.charAt(i);
numbers[i] = Integer.parseInt(Character.toString(string.charAt(i)));
}
//利用一个空的int型数组count,将numbers数组每个元素出现的次数存储在count数组中
for (int i = 0; i < string.length(); i++) {
a = numbers[i];
count[a]++;
}
//遍历count数组,打印每个数字出现的次数
for (int i = 0; i < count.length; i++) {
System.out.println(i + "出现了" + count[i] + "次");
}
}
}
解题思路:
在刚看到这个题的时候,思路很清新,遍历字符串将每个数字提取出来放到一个数组里,再用一个10个元素的空数组count[]去存储0-910个数字每次出现的次数,最后输出这个count数组,答案不就出来了吗???
然后,bug它来了!它踏着祥云走来了!报错了!
报错原因其实也很简单,String类的charAt(int index)方法返回的是一个char类型的字符,而numbers[]数组是int类型,存储的事ASCII值,必须将获取的字符型的数字转换成整型的数字,查了一下API,发现Character类没有直接将char类型转换为int类型的方法,但是有将char转换成string类型的方法,而String类又恰好有将String类转换成int型的方法,于是采用了曲线救国的办法,将char类型转换为string类型,再将string类型转换为int型,这才将这个小bug解决掉。
这部分的具体实现代码:
//将string分割为每个数字存储在numbers数组中
for (int i = 0; i < numbers.length; i++) {
//string.charAt(i)返回一个char类型的数字,思考怎么转为int类型
/*使用Character类的toString()方法转换为String类型,再使用Integer类的parseInt()方法转换为int类型*/
/*即:char c = string.charAt(i);
String s = Character.toString(c);
int i = Integer.parseInt(s);
*/
numbers[i] = Integer.parseInt(Character.toString(string.charAt(i)));
}
产生问题原因:
这个问题的产生根本原因是对常用类的API方法不熟,不清楚其具体的返回值类型,希望大家在日常学习工作中多看看API,做到清晰的记住API的常用方法。
小白java狗望与诸君共勉!