简体   繁体   English

无法弄清楚为什么int在Java中重复

[英]Can't figure out why int is duplicating in Java

I am creatings a simple Java program that in the main class asks for a string (input) and then prints out how many vowels (int count) and consonants are in the string. 我正在创建一个简单的Java程序,该程序在主类中要求一个字符串(输入),然后打印出字符串中有多少个元音(int计数)和辅音。 The number of vowels works perfectly however the number of consonants double, so the string "James" has 2 vowels and 6 consonants according to my program. 元音的数量非常合适,但是辅音的数量却增加了一倍,因此根据我的程序,字符串“ James”具有2个元音和6个辅音。

public class counter {

vowels p1 = new vowels();

public int con = 0;

public int count() {

    String input = p1.getInput();

    int i = 0;
    int count = 0;

    while (i < input.length()){

        if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'i' || input.charAt(i) == 'o' || input.charAt(i) == 'u') {

        count++;

        } else if (input.charAt(i) != ' ') {
            con++;
        }
    i++;
    }

    return count;

}

public int con() {
    return con;
}
}

您正在使用实例成员con来计数辅音,并且没有在count方法的开头对其进行初始化,因此多次调用该方法将导致无效计数。

seems like you are using int con=0; 似乎您正在使用int con = 0;

is used for consonant count so instead of using 用于辅音计数,而不是使用

else if (input.charAt(i) != ' ') {
        con++;
    }

simply use else { con++; } 只需使用else { con++; } else { con++; }

Alternate : subtract the vowel count from string length 'com = P1.length()-count;' 备用:从字符串长度'com = P1.length()-count;'中减去元音计数。

Try to set the variable con to zero at the begining of the method "count". 尝试在方法“ count”的开头将变量con设置为零。

con = 0;

I hope it works. 我希望它能起作用。

char ch;
for(int i = 0; i < str.length(); i ++)
        {
            ch = str.charAt(i);

            if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || 
            ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
                count ++;
            else 
                con;
       }

you had nod consider the case when vowels are in caps I solved this in my code 你点头考虑元音是大写的情况我在代码中解决了

hope my code helps you in this regard thanks.Happy coding 希望我的代码在这方面对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM