2

我应该编写一个简单的 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);
        }
    }
}
4

2 回答 2

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>虽然你正在做的方式不是一个坏方法,但如果你保持 a来存储 each 的计数,你会更好Vowel。您需要使用每个字符的初始计数 0 来初始化 Map,然后在读取的每个字符上,如果在 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
于 2012-10-22T19:28:42.247 回答
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
于 2012-10-22T20:14:53.633 回答