如何在Java中创建一个简单的元音计数器方法?

时间:2010-01-16 13:32:39

标签: java counter

这是我的方法:

public char[] ReturnAllVowels(String word)
{
    for (int i = 0; i < word.length(); i++)
    {
        if (word.contains("a" || "e" || "i" || "o" || "u"))     
        {

        }
    }        
}

它说||不能应用于String类。那怎么办呢?

6 个答案:

答案 0 :(得分:12)

使用正则表达式,您可以尝试。

int count = word.replaceAll("[^aeiouAEIOU]","").length();

答案 1 :(得分:1)

char ch = word.charAt (i);
if (ch == 'a' || ch=='e') {

}

答案 2 :(得分:1)

    String regex = "[aeiou]";               
    Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);   
    int vowelcount = 0;
    Matcher m = p.matcher(content);
    while (m.find()) {
      vowelcount++;
    }
    System.out.println("Total vowels: " + vowelcount);

答案 3 :(得分:0)

您可以使用Peter的代码来获取元音。

char[] vowels = word.replaceAll("[^aeiouAEIOU]","").toCharArray();

答案 4 :(得分:0)

这就是我这样做的方式

public static void main(String[] args) {
    // TODO code application logic here

    // TODO code application logic here
    String s;
    //String vowels = a;
    Scanner in = new Scanner(System.in);
    s = in.nextLine();

    for(int i = 0; i<s.length();i++){
        char v = s.charAt(i);
        if(v=='a' || v=='e' || v=='i' || v=='o' || v=='u' || v=='A' || v=='E' || v=='I' || v=='O' || v=='U'){
            System.out.print (v);
        }
    }
}

答案 5 :(得分:0)

以下是我使用Scanner完成的工作。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String userInput;
    int vowelA = 0, vowelE = 0, vowelI = 0, vowelO = 0, vowelU = 0; 

    System.out.println(welcomeMessage);
    userInput = scan.nextLine();
    userInput = userInput.toLowerCase();

    for(int x = 0; x <= userInput.length() - 1; x++) {
        if(userInput.charAt(x) == 97)
            vowelA++;
        else if(userInput.charAt(x) == 101)
            vowelE++;
        else if(userInput.charAt(x) == 105)
            vowelI++;
        else if(userInput.charAt(x) == 111)
            vowelO++;
        else if(userInput.charAt(x) == 117)
            vowelU++;   
    } 

    System.out.println("There were " + vowelA + " A's in your sentence.");
    System.out.println("There were " + vowelE + " E's in your sentence.");
    System.out.println("There were " + vowelI + " I's in your sentence.");
    System.out.println("There were " + vowelO + " O's in your sentence.");
    System.out.println("There were " + vowelU + " U's in your sentence.");
}