我是一名初学者程序员,我正在尝试制作一个非常简单的 Hangman 版本。我的代码有很大问题。这是我遇到问题的代码部分:
for(int i = 0; i <= wordLength - 1; i++ ) {
if (letter == theWord.charAt( i )) {
onemore=i+1;
System.out.println("This letter matches with letter number " + onemore + " in the word.");
***displayWord.charAt(i)=letter;***
System.out.println("The word so far is " + displayWord);
}
}
我遇到错误的部分两侧各有 3 个星号。
displayWord 是一个字符串,而 letter 是一个字符。
Netbeans 告诉我:
unexpected type
required: variable
found: value
我不知道问题是什么。
最佳答案
基本上,Java String
是不可变的,即内容无法更改。
您最好使用StringBuilder
。
String theWord = "This is a simple test";
char letter = 'i';
char changeTo = '-';
StringBuilder displayWord = new StringBuilder(theWord);
int i = theWord.indexOf(letter);
if (i != -1) {
System.out.println("This letter matches with letter number " + (i + 1) + " in the word.");
displayWord.setCharAt(i, changeTo);
System.out.println("The word so far is " + displayWord);
}
System.out.println(displayWord);
这会导致:
This letter matches with letter number 3 in the word.
The word so far is Th-s is a simple test
This letter matches with letter number 6 in the word.
The word so far is Th-s -s a simple test
This letter matches with letter number 12 in the word.
The word so far is Th-s -s a s-mple test
Th-s -s a s-mple test
现在简短的版本可能看起来像这样
String displayWord = theWord.repace(letter, changeTo);
关于java - 更改字符串中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876328/