2013-10-26 45 views
0

我有一個程序,我正在處理的是計算字符串中元音的數量。我有它的工作,但如果Y後面跟着一個輔音,我不能把它算在Y.我的VOWEL_GROUP是「AEIOUaeiou」,它返回普通元音的數量,但不是'y'。我看它的charAt(i),看看它是否由除了元音組中的一個字符之外的其他東西所預置。 感謝您的幫助。 這裏是輸入和輸出,顯示錯誤在包含Y的字符串中計算元音,如果其後跟輔音

OUTPUT to console 

Input 
play. Why! Who! 

There are 3 words in the file. 
There are 2 vowels in the file. 
There are Y 19 vowels in the file. 
There are 3 sentences in the file. 


// START of countThe Y Vowels******************************************** 
    int YvowelCount=0; 
    for(int i=0;i<myFile.length();i++){ 
     for(int j=0;j<VOWEL_GROUP.length();j++){ 
      if(myFile.charAt(i)=='y' && myFile.charAt(i-1)!= VOWEL_GROUP.charAt(j)){ 
        YvowelCount++; 
      } 
     } 
} 
// END of countThe Y Vowels************************************************** 
+0

你可以添加一些輸入輸出樣本? – Christian

+0

我不明白'myFile.charAt(i)-1'這個部分,你確定這是你的期望嗎? – Christian

回答

1

首先,才使用需要移動的y查出來你內心的循環。事實上,你根本不需要內部循環。改爲使用String#contains()

接下來,由於您需要檢查y後的字符,因此charAt()索引需要爲i+1。出於同樣的原因,您不需要檢查文件的最後一個字符,因此循環運行到小於myFile.length() - 1

int YvowelCount=0; 
for (int i=0; i < myFile.length() - 1; i++) { 
    if (myFile.charAt(i) == 'y') { 
     if (!VOWEL_GROUP.contains(myFile.charAt(i+1) + "")) { 
       YvowelCount++; 
    } 
    } 
} 


如果您需要檢查之前 y做到爲字符: (循環將從i = 1現在開始)

int YvowelCount=0; 
for (int i=1; i < myFile.length(); i++) { 
    if (myFile.charAt(i) == 'y') { 
     if (!VOWEL_GROUP.contains(myFile.charAt(i-1) + "") && 
        Character.isLetter(myFile.charAt(i-1))) { 
      YvowelCount++; 
    } 
    } 
} 

通知,調用Character.isLetter()消除假計數就像一個詞以y開頭。

+0

這會返回所有'y's在字符串中,「Play。Why,Who。」在「爲什麼」中會出現唯一的'y'元音,因爲它跟隨一個輔音。那就是我被卡住的地方。在'y'之前檢查字符,看看它是否是元音。 **我確實通過遞減my.File.charAt(i-1)來獲得這個工作,以便在'y'之前查看字符,它確實返回了正確數量的'y'元音。謝謝** – RamseyR

+0

引用你的問題:'如果Y後面跟着一個輔音,則計數Y.' –

+0

另外,執行'Character.isLetter()'檢查,如我的更新中所示,現在從'1'開始循環。 –

0

以下是錯誤的,你一定意味着我-1來表示另一個指標。你正在做的是在索引i處獲得角色,並使用1代替另一個角色。

myFile.charAt(i)-1 

除此之外,確保I-1,如果我是> 0

0
int YvowelCount=0; 
for (int i=0; i < myFile.length()-1; i++) { 
    if (myFile.charAt(i+1) == 'y') { 
     if (!VOWEL_GROUP.contains(myFile.charAt(i) + "")) { 
       YvowelCount++; 
    } 
    } 
} 

檢查此。

相關問題