0

I wrote a GUI program to guess a random number between 1 and 200. When I run it, I can't get it to execute correctly. I can guess the same number twice and sometimes it will say "too low", and sometime it say "too high". I must have something out of order which I tried playing with, but I'm at a lost as to why this isn't working. Here is my code:

    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                   

}

4

1 回答 1

7

每次按下“猜测”按钮时,您都会生成一个新的随机数。要么在加载 GUI 时执行一次,要么创建一个新按钮来重置游戏并将随机数生成代码放在那里。

于 2013-05-30T19:29:35.447 回答