hangman类中出现意外类型错误

时间:2015-01-18 13:43:33

标签: java

我正在对hangman class进行编码,并对unexpected type error有一点问题。此错误发生在this.hidden.charAt(i) = this.original.charAt(i);中。任何帮助将不胜感激。

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;      

        }


    };

2 个答案:

答案 0 :(得分:2)

String.charAt(int)不能在赋值语句的左侧使用。你不能用Java改变/变异String

改为使用StringBuilder.setCharAt(int index, char ch)

答案 1 :(得分:2)

charAt(int)中的String不能用于分配值。你可以使用类似的东西:

this.hidden.setCharAt(i, this.original.charAt(i));

以上在StringBuilder上工作,因为String是Java中的不可变类。在String情况下,您可以使用类似的内容(每次都生成一个新的String):

this.hidden = this.hidden.substring(0,i) + this.original.charAt(i) + this.hidden.substring(i);