我正在尝试制作数字猜谜游戏。当用户按下开始按钮时,程序将随机生成一个数字。然后,用户可以输入一个数字,然后在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);
}
}
我发现尝试读取随机生成的数字时我做错了什么,但我不知道如何正确执行。有小费吗?
答案 0 :(得分:1)
根据注释并根据您的代码,考虑以下类,其中,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变量范围”。