计算给定句子中的元音数量:
阅读用户的句子
创建一个变量(计数),将其初始化为0;
比较句子中的每个字符与字符{'a','e','i','o','u'}
如果发生匹配,则增加计数。
最后打印计数。
import java.util.Scanner; public class CountingVowels { public static void main(String args[]){ int count = 0; System.out.println("输入一个句子:"); Scanner sc = new Scanner(System.in); String sentence = sc.nextLine(); for (int i=0 ; i<sentence.length(); i++){ char ch = sentence.charAt(i); if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' '){ count ++; } } System.out.println("Number of vowels in the given sentence is "+count); } }
输出结果
输入一个句子: Hi how are you welcome to nhooo Number of vowels in the given sentence is 22