计算字符串中的元音和错误的输出?

时间:2017-05-19 12:14:59

标签: java string for-loop

我是java的新手,我想知道你是否可以帮助我。这是我的代码:

public static void main(String[] args) {

    int vowels = 0;

    Scanner input = new Scanner(System.in);

    System.out.println ("Enter a string: ");
        String string = input.nextLine();

    int length = string.length();

for (int i = 0; i <= length; i++) {

    String letter = string.substring(i, ++i);

    if (letter.equalsIgnoreCase("a")){vowels++;}    
    if (letter.equalsIgnoreCase("e")){vowels++;}
    if (letter.equalsIgnoreCase("i")){vowels++;}
    if (letter.equalsIgnoreCase("o")){vowels++;}
    if (letter.equalsIgnoreCase("u")){vowels++;}

}
    System.out.println ("The number of vowels in " + string + " is: " + vowels);
}

号码已关闭,但我无法弄清楚原因。

2 个答案:

答案 0 :(得分:0)

这是错误的

string.substring(i, ++i)

因为变量 i 已经在for-loop

中递增

所以你基本上是在字符串中跳过字符

实施正确的逻辑,使用正确的数据类型

    int length = string.length();

    for (int i = 0; i < length; i++) {
        char letter = string.charAt(i);
        System.out.println(letter);
        if (letter == 'a') {
            vowels++;
        } else if (letter == 'e') {
            vowels++;
        } else if (letter == 'i') {
            vowels++;
        } else if (letter == 'o') {
            vowels++;
        } else if (letter == 'u') {
            vowels++;
        }

    }

答案 1 :(得分:0)

以下是您可以尝试的另一种解决方案:

split方法会将字符串拆分为String数组。然后在你的for循环中,它将检查数组中的每个项目。

public static void main(String[] args) {

    int vowels = 0;

    Scanner input = new Scanner(System.in);

    System.out.println ("Enter a string: ");
        String string = input.nextLine();

    int length = string.length();

    String[] stringArray = string.split("");

for (int i = 0; i < length; i++) {   //I took out the = sign in your for loop arguments.

    if (stringArray[i].equalsIgnoreCase("a")){vowels++;}    
    if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
    if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
    if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
    if (stringArray[i].equalsIgnoreCase("u")){vowels++;}

}
    System.out.println ("The number of vowels in " + string + " is: " + vowels);
}