首页 > 解决方案 > (JFrame)如何读取随机数以不同的方法进行比较而不显示它?

问题描述

我正在尝试做一个猜数字游戏。当用户按下开始按钮时,程序会随机生成一个数字。然后,用户可以输入一个数字,程序将告诉用户他们需要提高还是降低,在 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);
    }
}

我想在尝试读取随机生成的数字时我做错了,但我不知道如何正确地做到这一点。有小费吗?

标签: javajframe

解决方案


从评论中并根据您的代码,考虑以下类,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变量范围”。


推荐阅读