所以這就是我想要做的。我拿一個給定的字符串,並創建一個新的字符串。新的字符串將與原始字符串相同,但會使輔音翻倍。例如,rabbit
變成rrabbitt
等等。它只會使尚未加倍的輔音翻倍。檢查一個字符串是否有元音,並創建一個新的字符串,使輔音加倍
這是我到目前爲止有:
// Returns a new string in which all consonants in the given string are doubled.
// Consonants that are already doubled are not doubled again.
// For example, doubleConsonants("rabbit") returns "rrabbitt".
// It is assumed that in the given string is alphabetic and that no character
// appears more than twice in a row.
// Parameters:
// s - given string
// Returns new string with all consonants doubled
----------------------------------------------------------------------------
public static String doubleConsonants(String s) {
String newString = "";
String vowels = "aeiouAEIOU";
for (int i = 0; i < s.length(); i++) {
boolean hasVowel = false;
for (int n = 0; n == 10; n++){
if (vowels.charAt(n) == s.charAt(i)) {
newString += s.charAt(i);
i++;
hasVowel = true;
break;
}
}
if (hasVowel = false && s.charAt(i) != s.charAt(i+1) && s.charAt(i) != s.charAt(i-1)) {
newString += s.charAt(i);
i++;
}
else if (hasVowel = false) {
newString += s.charAt(i);
i++;
}
}
return newString;
}
顯然有一些問題與「死代碼」和布爾hasVowels是「不使用」。我在搞什麼?
您的for循環從不起作用。用for(int n = 0; n == 10; n ++)。 for循環只在條件n == 10是真的時才起作用,永遠不會。 – Moonstruck
我以爲n = 0是開始點,n == 10是結束... – Muldawg2020
我該如何改變它,所以它會經歷10次迭代? – Muldawg2020