本示例是布置给学生作业的参考程序,其他初学者亦可参考。
程序题目:设计并实现一个程序,读入用户输入的一个字符串,然后确定并打印输出每一个小写元音字母(a、e、i、o、u)在整个字符串中出现的次数。每一个元音字母用不同的计数器统计,同时也打印输出非元音字母的个数。
依题意,我们只考虑小写字母。这其中的难点是,一个字符串中除了字母,还有空格、标点符号和数字等非字母字符。统计5个元音字母容易实现,但是非元音字母有21个,若写21个判断语句太麻烦;若用字符串长度减去元音字母个数,则忽略了空格、标点符号和数字等非字母字符的情况。因此,本题的关键是如何把统计范围限定在小写字母范围内。为达到这一目的,我们可以使用字符的Unicode编码。小写字母的Unicode编码从97到122,我们获取字符的Unicode编码,然后与以上范围比对,即可判定该字符是否是小写字母。获取字符的Unicode编码很简单,直接把字符强制转换类型为int即可。
解决了这个关键问题后,解题的思路就清晰了。首先创建两个ArrayList对象,都有6个元素。一个保存5个元音和字母c(代表所有辅音),相对应地,另一个ArrayList对象分别保存对应字母的个数。这里需要注意的是,ArrayList对象不保存基本数据类型,因此在下面的程序中虽然直接对ArrayList对象存取字符和整型值,但实际上执行了自动装箱/拆箱操作。即把字符和整数往ArrayList对象存储时,自动包装成了相应的Character对象和Integer对象;而从中读取时,又自动转换成了相应的char类型和int类型。相关方法的用法,可查阅JAVA API文档。程序如下:
- import java.util.Scanner;
- import java.util.ArrayList;
- public class LetterStatistics
- {
- public static void main(String[] args)
- {
- //sentence保存用户输入的字符串
- String sentence = null;
- //ch保存从字符串中截取的字符
- char ch = 'a';
- int index = 0;
- //unicode保存字符的unicode编码
- int unicode = 0;
- int temp = 0;
- Scanner scan = new Scanner(System.in);
- //保存字母的ArrayList
- ArrayList<Character> letter = new ArrayList<Character>();
- //添加5个元音,注意这里有装箱操作,即把
- //字符包装为对应的Character对象
- letter.add('a');
- letter.add('e');
- letter.add('i');
- letter.add('o');
- letter.add('u');
- //添加字母c,代表所有非元音字母
- letter.add('c');
- //计数器ArrayList,第0个是字母a的计数器,其它以此类推
- ArrayList<Integer> counter = new ArrayList<Integer>();
- //这里同样有装箱操作
- counter.add(0);
- counter.add(0);
- counter.add(0);
- counter.add(0);
- counter.add(0);
- counter.add(0);
- System.out.println("请输入一个字符串:");
- sentence = scan.nextLine();
- int length = sentence.length();
- //扫描字符串,提取其中的每个字母来处理
- for(index = 0; index < length; index++)
- {
- //提取下标为index的字符
- ch = sentence.charAt(index);
- //获取字符的Unicode编码
- unicode = (int)ch;
- //只处理小写字母
- if(unicode <= 122 && unicode >=97)
- {
- switch(ch)
- {
- case 'a':
- //自动拆箱,把Integer类型值自动
- //转换为int类型
- temp = counter.get(0);
- temp++;
- //把temp值赋给counter中的第0个元素,
- //即元音字母a的计数器。自动装箱,
- //把int类型自动包装为Integer类型
- counter.set(0, temp);
- break;
- //以下类似
- case 'e':
- temp = counter.get(1);
- temp++;
- counter.set(1, temp);
- break;
- case 'i':
- temp = counter.get(2);
- temp++;
- counter.set(2, temp);
- break;
- case 'o':
- temp = counter.get(3);
- temp++;
- counter.set(3, temp);
- break;
- case 'u':
- temp = counter.get(4);
- temp++;
- counter.set(4, temp);
- break;
- default:
- temp = counter.get(5);
- temp++;
- counter.set(5, temp);
- }
- }
- else
- {
- //若当前字符不是小写字母,则不做任何处理,
- //继续下次循环,处理下一个字符
- continue;
- }
- }
- length = counter.size();
- //打印输出各种字母的个数
- for(index = 0; index < length - 1; index++)
- {
- System.out.println("字符串中元音"
- + letter.get(index)
- + "的个数是:"
- + counter.get(index)
- + "。");
- }
- System.out.println("辅音的个数是:" + counter.get(index));
- }
- }
运行结果示例: