【问题标题】:Use string methods to find and count vowels in a string?使用字符串方法查找和计算字符串中的元音?
【发布时间】:2016-08-09 08:19:31
【问题描述】:

当我的代码编译时,它会为我提供多个元音输出。几乎就像它在检查每个字符后给我一个输出一样。我如何让它只给出一个输出,包括我所有的元音和其他元音。在 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);
    }
  }
}

【问题讨论】:

    标签: java charat


    【解决方案1】:

    你在 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);
    ...
    

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 2021-11-02
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      相关资源
      最近更新 更多