java - (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);
}
}
我想在尝试读取随机生成的数字时我做错了,但我不知道如何正确地做到这一点。有小费吗?
解决方案
从评论中并根据您的代码,考虑以下类,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变量范围”。
推荐阅读
- node.js - Express 应用程序不允许我检查 req 中的内容
- python - 如何最好地将使用 Python 搁置库 (bsddb) 的腌制 Python 字典转换为具有字典键元组值的 JSON 文件
- javascript - Safari ITP 2.0 存储访问 API - 在 hasStorageAccess 中嵌套 requestStorageAccess 时遇到问题 - 非嵌套作品
- sql - SQL Server 服务代理和链接服务器
- python - 求解矩阵方程 AB = BC,已知 A 和 C
- mysql - MySQL/MariaDB 删除具有长用户名的用户失败
- mysql - Laravel 数据库 sql
- r - 使用`sub`重命名数据框中的列
- c++ - MSYS2 上的 gcc 8.2.1 的特征编译错误
- java - 我希望输出适应年龄