2014-10-08 108 views
-4

我想知道如何計算由用戶輸入的字母出現在用戶也輸入的字符串中的次數。我必須使用循環和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);` 
+2

更換'如果(sentence.charAt(posotion)=字母){''與如果(sentence.charAt(posotion)==字母){',對於初學者。你把一個分配,而不是比較。 – AntonH 2014-10-08 23:20:31

+2

'sentence.charAt(posotion)' - >'sentence.charAt(position)' – jpw 2014-10-08 23:20:56

+0

那麼這將有助於如果我可以拼寫... – FirstYearStudent 2014-10-08 23:23:14

回答

1

首先,你有一個錯字在你的if語句:

sentence.charAt(posotion) 

應該

sentence.charAt(position) 

然後,你要分配,而不是測試平等:

if (sentence.charAt(position) = letter) { 

應該是

if (sentence.charAt(position) == letter) { 

接下來,您正在比較一個char和該if語句中的字符串。有幾種方法來解決這個問題,一種方法是(假設letter至少有一個字符):

if (sentence.charAt(position) == letter.charAt(0)) { 

最後,你可能不檢查什麼過去的字符串,以便結束:

for (position=0; position<=sentence.length(); position++) { 

應該是

for (position=0; position<sentence.length(); position++) { 
+0

我已經修復了愚蠢的錯誤(明顯是漫長的一天),現在有for語句如下:
for(position = 0; position 該代碼仍然不會編譯並讀取「無法比較的類型:char和java.lang.String」。是否有另一種我應該使用的變量類型? – FirstYearStudent 2014-10-08 23:36:57

+0

這是因爲'charAt()'返回一個'字符'而'字母'是'字符串'。回答編輯。 – Jason 2014-10-08 23:41:57

+0

所以我應該從技術上來說只是把句子放在句子上。(位置)== letter.charAt(0)?哇,我看起來殘疾人試圖找出這個網站的格式... – FirstYearStudent 2014-10-08 23:48:28