java - 在 Java 中分别计算元音
问题描述
示例输出:
输入一个字符串:你好
字符串中每个元音的数量:
a: 0
e: 1
i: 0
o: 1
u: 0
other characters: 3
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int count = 0;
System.out.println("Enter a string: ");
Scanner myObject = new Scanner(System.in);
String anyWord = myObject.nextLine();
for (int i = 0; i < anyWord.length(); i++) {
char vowelA = anyWord.charAt(i);
if (vowelA == 'a' || vowelA == 'A') {
count++;
}
}
System.out.println("a: " + count);
}
}
这是我正在编写的代码,但我不知道下一步该怎么做......需要你的帮助......
解决方案
即使其他人有工作,我也会在这里添加我的解决方案。在我看来,为您正在寻找的每个独特项目创建一堆变量是不好的做法。如果您现在也想接受y
作为元音怎么办?
这是我的解决方案,它使用一个字符数组来定义应该计算哪些字符。然后我们创建一个 Hashmap,其中键是字符,值是字符串中每个字符出现的计数。然后我们遍历字符串,如果键已经存在于 Hashtable 中,则增加 Hashtable 中的计数值。请记住,我们之前通过这样做准备了 Hashtable。最后,我们打印出所有键及其相关值。
import java.util.*;
public class Main {
public static void main(String []args){
// List of vowels.
char vowel_characters[] = {'a', 'e', 'i', 'o', 'u'};
// Add vowels to dictionary, assign value to zero.
Hashtable vowels = new Hashtable();
for (char vowel : vowel_characters) {
vowels.put(vowel, 0);
}
// The input string.
String input = "Hello, world!";
// Check if the character at index `i` is in the dictionary, if so then
// add 1 to its counter.
for (int i = 0; i < input.length(); i++) {
char vowel = input.charAt(i);
if (vowels.containsKey(vowel)) {
vowels.put(vowel, (int)vowels.get(vowel) + 1);
}
}
// Print the results/
for (Object vowel : vowels.keySet()) {
System.out.println((char)vowel + ": " + vowels.get(vowel));
}
}
}
推荐阅读
- reactjs - 优化应用程序的路由和 React 延迟加载,登陆页面上有 2 个部分
- python - WinError 3 系统找不到指定的路径,即使路径是有效的
- python - 清除终端中的最后 n 行
- discord.py - 在列表不和谐python JSON文件中检测相同的项目
- python - 我无法理解为什么我的函数失败 - 它必须与 parseUser 函数有关
- azure-databricks - 如何检查 azure databricks 和 HDinsight 上的数据沿袭?
- python - 如何从屏幕上删除单个 pygame 绘图?
- python - 如何逐行比较旧数据框和新数据框(如果没有匹配,那么我需要插入空白行)?
- vue.js - 如何注册组件