[英]Can't figure out why int is duplicating in Java
我正在創建一個簡單的Java程序,該程序在主類中要求一個字符串(輸入),然后打印出字符串中有多少個元音(int計數)和輔音。 元音的數量非常合適,但是輔音的數量卻增加了一倍,因此根據我的程序,字符串“ 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
方法的開頭對其進行初始化,因此多次調用該方法將導致無效計數。
似乎您正在使用int con = 0;
用於輔音計數,而不是使用
else if (input.charAt(i) != ' ') {
con++;
}
只需使用else { con++; }
else { con++; }
備用:從字符串長度'com = P1.length()-count;'中減去元音計數。
嘗試在方法“ count”的開頭將變量con設置為零。
con = 0;
我希望它能起作用。
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;
}
你點頭考慮元音是大寫的情況我在代碼中解決了
希望我的代碼在這方面對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.