我正在开发一款介于1到100之间的猜谜游戏的应用。我正在编写的当前版本使玩家7试图找到正确的猜谜。我创建了一个变量来显示玩家还剩下多少个猜测,但是一旦玩家猜测了,猜测的数量就会减少一个以上(通常是两个)。
所以基本上是numberOfGuesses var。每次运行checkGuess()方法时都会减少。我曾尝试将减量放置在事件监听器中,以供播放器按下按钮时使用,但它仍会减少一个以上。如果播放器也单击鼠标按钮,则存在一个setOnClick侦听器,而另一个用于Enter按钮的侦听器。当我在游戏中使用按钮时,它会适当减小。当我使用ENTER按钮时,它会减少2。当我按ENTER键时,它是否正在运行按钮侦听器?
我试图更改numberOfGuesses的减量-到--numberOfGuesses;
我尝试将其分配为numberOfGuesses = numberOfGuesses-1;
这是连接到w GUI的变量和checkGuess()方法
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
private int numberOfTries = 7;
public void checkGuess() {
String guessText = txtGuess.getText().toString();//
String message = "";
try {
--numberOfTries;
int guess = Integer.parseInt(guessText);
if (guess > theNumber)
message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";
else if (guess < theNumber)
message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";
else{
message = guess +
" is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
newGame();
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
} finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
newGame()方法生成一个新的随机数
public void newGame(){
theNumber = (int)(Math.random() * 100 + 1);
numberOfTries = 7;
}
这是在执行应用程序时运行的方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = (EditText) findViewById(R.id.txtGuess);
btnGuess = (Button) findViewById(R.id.btnGuess);
lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkGuess();
}
});
txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
checkGuess();
return true;
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
我期望numberOfGuesses从7减少到6,但是当我使用enter时,实际输出从7减少到5,它可以按我想要的按钮单击方式工作(或至少显示为7到5),
最佳答案
在选择文本字段时按Enter键将触发OnEditorActionListener(据我所知,任何其他更改也将触发)。您是否尝试过通过actionId过滤该监听器,以确保它仅针对回车键关闭?