我想知道如何計算由用戶輸入的字母出現在用戶也輸入的字符串中的次數。我必須使用循環和if/else語句。我認爲我在正確的軌道上,但編譯時(使用BlueJ)遇到了錯誤消息「無法找到符號 - 變量位置」。任何幫助非常感謝,謝謝。Java:如何使用循環統計字符串中的字符?
String input;
String sentence;
String letter;
int times=0;
int position;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a string: ");
input = kb.nextLine();
sentence = input.toLowerCase();
System.out.print("Thank you.\nPlease enter the character you wish to be counted: ");
letter = kb.next();
for (position=0; position<=sentence.length(); position++) {
if (sentence.charAt(position) == letter) {
times++;
}
}
System.out.print("There are "+times+" ocurrances of the letter "+letter
+" in the string "+sentence);`
更換'如果(sentence.charAt(posotion)=字母){''與如果(sentence.charAt(posotion)==字母){',對於初學者。你把一個分配,而不是比較。 – AntonH 2014-10-08 23:20:31
'sentence.charAt(posotion)' - >'sentence.charAt(position)' – jpw 2014-10-08 23:20:56
那麼這將有助於如果我可以拼寫... – FirstYearStudent 2014-10-08 23:23:14