使用字符串方法查找和计算字符串中的元音?

时间:2016-04-17 17:14:56

标签: java charat

当我的代码编译时,它给了我元音的多个输出。几乎就像它在检查每个角色后给我一个输出。我如何让它只用我的所有元音和其他的一个输出。在1输出??

请帮忙......

import java.util.*;

public class Lowercasevowelcounter {

    public static void main(String[] args) {

    int a=0, e=0, x=0;
    int u=0, o=0, other=0;

    String text;
    Scanner sc = new Scanner(System.in);


    System.out.println("Enter a string of words : ");
    text = sc.nextLine();

    for (int i = 0; i < text.length(); i++){
        char c = text.charAt(i);

        if (c == 'a') a++;

        else if (c == 'e')  
          e++;

        else if (c == 'i')  
          x++;

        else if (c == 'o')
          o++;

        else if (c == 'u')
          u++;

        else 
          other++;

        System.out.println("a: " + a + "\n" +
                "e: " + e + "\n" +
                "i: " + x + "\n" +
                "o: " + o + "\n" +
                "u: " + u + "\n" +
                "other: " + other);
    }
  }
}

1 个答案:

答案 0 :(得分:3)

你在for循环中有System.out.println(...)。尝试将其提取到for循环之外。

...
for (int i = 0; i < text.length(); i++){
    char c = text.charAt(i);

    if (c == 'a')a++;
        else if (c == 'e')  e++;
        else if (c == 'i')  x++;
        else if (c == 'o')  o++;
        else if (c == 'u')  u++;
    else 
    other++;
}

System.out.println("a: " + a + "\n" +
        "e: " + e + "\n" +
        "i: " + x + "\n" +
        "o: " + o + "\n" +
        "u: " + u + "\n" +
        "other: " + other);
...