java元音计数器使用开关方法 [英] java Vowel Counter Using Switch Method
问题描述
我应该编写一个简单的 java 应用程序,计算用户输入的字符串中的每个元音并输出每个元音出现的次数.
I am supposed to write a simple java application that counts each vowel in a string entered by the user and outputs the number of time each vowel occurs.
我不明白为什么我的代码会检查字符串中的每个单词.我为每个单词获得了适量的元音.这是我所拥有的:
I don't understand why my code is checking each individual word in my string. I am getting the right amount of vowels for each word. Here is what I have:
import java.util.Scanner;
public class VowelAnalyst
{
//
//
public static void main (String[] args)
{
String userString;
int aCount = 0, eCount = 0, iCount = 0, oCount = 0, uCount = 0;
char vowels;
Scanner scan = new Scanner (System.in);
System.out.println ("enter string:");
userString = scan.nextLine();
for (int count = 0; count < userString.length(); count++)
{
vowels = userString.charAt(count);
switch (vowels)
{
case 'a':
aCount++;
break;
case 'e':
eCount++;
break;
case 'i':
iCount++;
break;
case 'o':
oCount++;
break;
case 'u':
uCount++;
break;
default:
System.out.println ("Please enter valid string.");
}
System.out.println ("a: " +aCount);
System.out.println ("e: " +eCount);
System.out.println ("i: " +iCount);
System.out.println ("o: " +oCount);
System.out.println ("u: " +uCount);
}
}
}
推荐答案
也许您应该将下面的打印语句移出 for 循环,否则它们将在比较每个字符后打印计数:-
May be you should move your below print statements out of your for loop, else they will print count after every character compared: -
System.out.println ("a: " +aCount);
System.out.println ("e: " +eCount);
System.out.println ("i: " +iCount);
System.out.println ("o: " +oCount);
System.out.println ("u: " +uCount);
更新:-
虽然你这样做的方式还不错,但如果你维护一个Map
来存储每个Vowel
的计数会更好>.您需要使用每个字符的初始计数 0 来初始化您的 Map,然后在读取每个字符时,如果在 Map 中找到匹配,只需增加计数.
Although the way you are doing is not a bad way, but you would be better if you maintain a Map<Character, Integer>
to store the count of each Vowel
. You need to initialize your Map with an initial count of 0 for each character, and then on each character read, just increment the count, if match is found in Map.
这是一个示例片段:-
// This is `double-braces` initialization.
// You can rather initialize your Map in a way you are comfortable with
Map<Character, Integer> vowels = new HashMap<Character, Integer>() {
{
put('a', 0);
put('e', 0);
put('i', 0);
put('o', 0);
put('u', 0);
}
}; // Note the semi-colon here
然后你在 for 循环中从字符串中读取每个字符的代码:-
And then your code of reading each character from string in for loop: -
for (int count = 0; count < userString.length(); count++)
{
char ch = userString.charAt(count);
ch = Character.toLowerCase(ch);
if (vowels.containsKey(ch)) {
vowels.put(ch, vowels.get(ch) + 1);
}
}
System.out.println(vowels); // Will print each vowels with respective count
这篇关于java元音计数器使用开关方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!