我正在尝试制作一个猜数字游戏。当用户按下开始按钮时,程序会随机生成一个数字。然后用户可以输入一个数字,程序会告诉用户是否需要更高或更低,猜测 8 次后程序停止。
我已经成功地生成了一个随机数并编写了一个允许用户猜测 8 次的循环。没有编译错误,但按下“guessBtn”时出现很多错误。这是我的代码:
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Random rand = new Random();
int getal = rand.nextInt(100)+1;
}
private void guessBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String randomNumTxt = startBtn.getText();
int getal = Integer.parseInt(randomNumTxt);
String gokNumTxt = guessTxt.getText();
int gok = Integer.parseInt(gokNumTxt);
int aantalGok = 0;
while ((gok != getal) && (aantalGok <9)){
if (gok < getal){
antwoordLbl.setText("Hoger!");
aantalGok++;
}
if (gok > getal){
antwoordLbl.setText("Lager!");
aantalGok++;
}
}
if (gok == getal){
antwoordLbl.setText("Geraden!");
}
else if (aantalGok == 8){
antwoordLbl.setText("Jammer, het getal was "+getal);
}
}
我认为在尝试读取随机生成的数字时我做错了什么,但我不知道如何正确执行。有小费吗?
最佳答案
根据注释并根据您的代码,考虑下面的类,其中 actual
存储每次单击“开始”按钮时随机生成的值。作为实例变量(不是注释中提到的类变量),该值在类的同一实例的方法之间仍然可用。
public class MyFrame extends JFrame implements ... {
// keep track of a randomly generated value
private int actual; // part of the class, not within a method
// each instance of the class will have its own value
// the variable exists as long as the instance exists
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Random rand = new Random(); // this could also be an instance variable instead of creating a new one each time
// int getal = rand.nextInt(100)+1; getal would be a local method variable and is lost when the method returns
actual = rand.nextInt(100)+1; // keep track of the random value
}
private void guessBtnActionPerformed(java.awt.event.ActionEvent evt) {
...
int guess = ... // whatever the user guessed
if (guess == actual) {
...
} else if (guess > actual) {
...
} else {
...
}
}
}
进一步阅读:搜索“java 变量作用域”。
关于java - (JFrame) 如何读取随机数以用不同的方法进行比较而不显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725792/