我应该写一个简单的java应用程序来计算用户输入的字符串中的每个元音,并输出每个元音发生的时间。
我不明白为什么我的代码会检查字符串中的每个单词。我为每个单词得到了正确数量的元音。这就是我所拥有的:
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);
}
}
}
答案 0 :(得分:3)
可能你应该将你的下面的印刷语句移出你的for循环,否则他们会在每个角色比较后打印计数: -
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<Character, Integer>
来存储每个Vowel
的数量,你会更好。您需要初始化Map,每个字符的初始计数为0,然后在每个字符读取时,只需增加计数,如果在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循环中的字符串中读取每个字符: -
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
答案 1 :(得分:0)
你们真的需要创建一个地图来存储一些角色吗?
public static void main(String[] args)
{
char[] vowels = "aeiouAEIOU".toCharArray();
String text = "I am a Java programmer";
int[] vowelsCount = new int[vowels.length];
for (char textChar: text.toCharArray())
{
for (int i = 0; i < vowels.length; i++)
{
char vowel = vowels[i];
if (vowel == textChar)
{
vowelsCount[i]++;
break;
}
}
}
for (int i = 0; i < vowelsCount.length; i++)
{
System.out.println(vowels[i] + " - " + vowelsCount[i]);
}
}
输出:
a - 5
e - 1
i - 0
o - 1
u - 0
A - 0
E - 0
I - 1
O - 0
U - 0