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