【发布时间】:2019-05-30 01:53:56
【问题描述】:
我正在制作一个应用程序,它是 1 到 100 之间的猜谜游戏。我正在编写的当前版本让玩家 7 尝试找到正确的猜测。我创建了一个变量来显示玩家还剩下多少猜测,但是一旦玩家猜到了,猜测的数量就会减少不止一个(通常是两个)。
所以基本上 numberOfGuesses 变量。每次运行 checkGuess() 方法时都会递减。当玩家按下按钮时,我尝试将减量放在事件侦听器中,但它的减量仍然不止一个。如果玩家也单击鼠标按钮,则有一个 setOnClick 侦听器,另一个用于输入按钮。当我在游戏中使用按钮时,它会正确递减。当我使用 ENTER 按钮时,它会减 2。当我按下 ENTER 时它是否正在运行按钮监听器?
我尝试从 numberOfGuesses 更改减量--;到 --numberOfGuesses;
我尝试将其分配为 numberOfGuesses = numberOfGuesses - 1;
这是连接到图形用户界面的变量,以及 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,但实际输出从 7 减少到 5,当我使用 enter 时,它可以按我想要的按钮单击(或至少显示为 7 到 5) ,
【问题讨论】:
标签: java android variable-assignment