Reputation: 21
I am coding a hangman class
and have a little problem with an unexpected type error
. This error is in the this.hidden.charAt(i) = this.original.charAt(i);
. Any help will be appreciated.
public class HangmanClass {
private ArrayList<String> words = new ArrayList();
private String word;
private final static char HIDECHAR = '*';
private String original;
private String hidden;
public void HangmanWord(String original){
this.original = original;
this.hidden = this.hideWord();
}
public String getWord() {
words.add("greetings");
words.add("cheese");
words.add("making");
words.add("juvenile");
words.add("car");
word = words.get(new Random().nextInt(words.size()));
return word;
}
private String hideWord() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
sb.append(HIDECHAR);
}
return sb.toString();
}
public boolean checkInput(char input){
boolean found = false;
for (int i = 0; i < this.original.length(); i++) {
if (this.original.charAt(i) == input) {
found = true;
this.hidden.charAt(i) = this.original.charAt(i);
}
}
return found;
}
};
Upvotes: 0
Views: 55
Reputation: 9413
The charAt(int)
in String
cannot be used to assign values. You can use something like:
this.hidden.setCharAt(i, this.original.charAt(i));
The above works on StringBuilder
, as String
is an immutable class in Java. In String
case you can use something like (generates a new String
every time):
this.hidden = this.hidden.substring(0,i) + this.original.charAt(i) + this.hidden.substring(i);
Upvotes: 2
Reputation: 72884
String.charAt(int)
cannot be used on the left-hand side of an assignment statement. And you cannot change / mutate String
s in Java.
Use a StringBuilder.setCharAt(int index, char ch)
instead.
Upvotes: 2