我写了一个GUI程序来猜测1到200之间的随机数。当我运行它时,我无法让它正确执行。我可以两次猜出相同的数字,有时候会说“太低”,有时会说“太高”。我必须尝试一些我尝试玩的游戏,但是我为什么这样做不起作用而迷失了方向。这里是我的代码:如何在GUI中生成一个随机数字?
import java.util.Random;
public class GuessPanel extends javax.swing.JPanel {
protected Random random;
protected int x;
protected int n;
public GuessPanel() {
initComponents();
}
@SuppressWarnings("unchecked")
**Generated Code**
private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
random = new Random();
String s = userField.getText();
int i = 200;
x = random.nextInt(i);
n = Integer.parseInt(s);
if (x == n)
{
answerLabel.setText("You guessed right!!!");
}
else if (x > n)
{
answerLabel.setText("Your guess is too low, guess again");
}
else if (x < n)
{
answerLabel.setText("Your guess is too high, guess again");
}
}
// Variables declaration - do not modify
private javax.swing.JLabel answerLabel;
private javax.swing.JButton guessButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField userField;
// End of variables declaration
}
它正在做你正在问的事情。 – wazy