I can get GUI run as i want to... Can any1 help me to look at it!
Write a application that plays “guess the number” as follows: Your application chooses the number to be guessed by selecting an integer at random in the range 1-100. The application then displays the following in a label:
I have a number between 1 and 100. Can you guess my number?
A JTextField should be used to input the guess. As each guess is input, a hint message will be output to tell the user if the number enters is too low or too high.
A JButton should be provided to allow the user to play the game again. When the JButton is clicked, a new random number should be generated.
(Size of the window is width: 280 pixels and height: 150 pixels)
import java.util.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JOptionPane; public class Q3 { JTextField number; JLabel lbl2; double num1=0.0; Q3(){ JFrame frm = new JFrame("Guessing Game"); frm.setSize(280,150); frm.setTitle("Guessing Fame"); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lbl = new JLabel("I have number between 1 and 100"); lbl2 = new JLabel("Can you guess my number?"); number = new JTextField(15); JButton btn = new JButton("New Game"); JPanel panel = new JPanel(); number.addActionListener(new ButtonHandler()); panel.add(lbl); panel.add(lbl2); panel.add(number); panel.add(btn); frm.add(panel); frm.setVisible(true); } public static void main(String[] args) { Q3 game = new Q3(); Random generator = new Random(); int n1=generator.nextInt(101); System.out.println(n1); } private class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e) { int num1; int guess = 0; String num=number.getText(); try{ num1 = Integer.parseInt(num); do{ //num1 = Integer.parseInt(num); /*if(num1==guess){ lbl2.setText("Congratulations,You guess is correct!"); } else*/ if(num1<=guess) lbl2.setText("Too low, try a higher number"); else if(num1>=guess) lbl2.setText("Too high, try a lower number"); else lbl2.setText("Congratulations,You guess is correct!"); }while(guess!=num1); number.setText(""); } catch(Exception ex){ JOptionPane.showMessageDialog(null,"Please Enter the correct input"); number.setText(""); } } } }
Pls any1 can help me with this???
TQ!