Hello there.
Currently, I am trying to develop a graphical number guessing game in JAVA. This is my first project in java.
Here is an insight in the application:
When the application is first opened, a random number (1-100) is assigned to a variable. When the user enters their guess in the textbox and presses "submit", the two integers are compared and a result is displayed (EG: Number too high/low). This is done in the ActionPerformed. Now the issue is, whatever number the user enters, they get "Number too low" everytime! I even outputted the generated number via System.out.println and still it displays "Number too low." I need help. Execute the code yourself!
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.*;
public class GuessMyNumber {
public static void main(String s[]) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100);
int numberOfTries = 0;
String guess = null;
JFrame frame = new JFrame("GuessMyNumber");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("Guess a number between 1-100");
JButton button = new JButton();
button.setText(">> Submit your guess <<");
JTextField userguess = new JTextField("1");
int parseduserguess = Integer.parseInt(userguess.getText());
JLabel result = new JLabel("");
Font bigFont = userguess.getFont().deriveFont(Font.BOLD);
userguess.setFont(bigFont);
panel.add(label);
panel.add(userguess);
panel.add(button);
frame.add(panel);
panel.add(result);
frame.setSize(300, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(parseduserguess > numberToGuess){
result.setText("Number too high!");
}else if(parseduserguess < numberToGuess){
result.setText("Number too low");
}
}
});
}
}
I appreciate any support or feedback given!