2 回答

TA貢獻1869條經驗 獲得超4個贊
假設您有一個啟動,例如 .
用戶輸入字母,應該發生的事情是StringItaliai
------ > I---i-
讓我們首先將待猜到的版本轉換為虛線版本String
final String toBeGuessed = "Italia"; // Italia
final String dashed = toBeGuessed.replaceAll(".", "-"); // ------
現在,用戶以猜測的字母形式輸入。我們將其轉換為小寫字母,以便以后進行比較。i
final char letter = Character.toLowerCase('i');
我們需要做的是更新虛線,為此我們將使用.
使用 a 允許我們設置單個字符。StringStringBuilderStringBuilder
// Create the StringBuilder starting from ------
final StringBuilder sb = new StringBuilder(dashes);
// Loop the String "Italia"
for (int i = 0; i < toBeGuessed.length(); i++) {
final char toBeGuessedChar = toBeGuessed.charAt(i);
// Is the character at the index "i" what we are looking for?
// Remember to transform the character to the same form as the
// guessed letter, maybe lowercase
final char c = Character.toLowerCase(toBeGuessedChar);
if (c == letter) {
// Yes! Update the StringBuilder
sb.setCharAt(i, toBeGuessedChar);
}
}
// Get the final result
final String result = sb.toString();
result將是 .I---i-

TA貢獻1824條經驗 獲得超6個贊
就像在Java中一樣,字符串是不可變的,因此您無法用另一個字符串替換任何字符串。
hintsQuestionString = hintsQuestionString.replace(hintsQuestionString.charAt(k), letterChar);
上面的行在Java中不起作用。
您可以使用 StringBuilder 類來替換字符串
或
您不必吐出字符串,因為它在Java中不起作用,因為Java中的String類是不可變的。
您只需在文本視圖中設置文本即可
你從用戶那里得到的這個字符串 String hintsQuestionString = hintsQuestion.getText().toString();
然后使用equals方法比較整個字符串,如果輸入的字符串匹配,則必須設置文本。我已經自己獲取了 countryName 變量,您必須將此字符串替換為您采用的變量。
if(countryName.equals(hintsQuestionString))
{
hintsQuestion.setText(hintsQuestionString);
}
我希望,這會幫助你。
添加回答
舉報