0
public class HangmanRoughActivity extends Activity {
    private EditText userLetter;
    private Button checkButton;
    private TextView text;
    protected int count = 6;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        start();
    }

    private void start() {
        int i;
        userLetter = (EditText) findViewById(R.id.letter);
        checkButton = (Button) findViewById(R.id.go);
        text = (TextView) findViewById(R.id.display);
        Random rand = new Random();
        int myrand = rand.nextInt(4);
        String[] questions = {"srk", "nandu", "kartheek", "kishore", "ravitejaG"}; //some random strings
        final String question = questions[myrand]; //selects a string from the above strings
        final char answer[] = new char[question.length()];
        for (i = 0; i < question.length(); i++) {
            answer[i] = '_'; //if "srk" is selected answer will be _ _ _ initially
        }
        text.setText(answer, 0, i); //if "srk" is selected,setting the textview to _ _ _
        checkButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int i = 0;
                char userEntry = userLetter.getText().charAt(0);
                String stringAnswer = answer.toString();
                if (question == stringAnswer) {
                    text.setText("Congratulations.You won");
                } else {
                    if (count > 0) {
                        int occurence;
                        char c;
                        for (i = 0, occurence = 0; i < question.length(); i++) {
                            c = question.charAt(i);
                            if (userEntry == c) {
                                answer[i] = c; //if 's' is entered by user,answer becomes s _ _
                                occurence++;
                            }
                        }
                        if (occurence == 0) //if the letter entered by user is not present in the question
                        {
                            text.append("You have" + count + "chances to go");
                            count--;
                        }
                        text.setText(answer, 0, i);
                    }
                }
            }
        });
    }
}

上面的代码是一个简单的刽子手控制台游戏。我无法附加“你有”+计数+“机会”行,也无法打印“恭喜你赢了”。为什么会这样?对不起冗长的代码

4

3 回答 3

2

使用String.equalsorString.equalsIgnoreCase比较当前你正在使用的字符串==,它用于比较字符串对象内字符内的两个对象引用。

于 2013-03-15T13:27:50.593 回答
0

即使我添加了附加语句,我还是用“text.setText(answer, 0, i);”行覆盖了 textview .所以setText和append命令的顺序需要互换。

于 2013-03-15T13:42:38.960 回答
0

像往常一样尝试 text.setText();。它会起作用的。

text.setText("You have"+count+"chances to go");
于 2013-03-15T13:27:59.733 回答