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!

I apologise for the code being too messy. I spent hours trying to resolve the problem but still failed. This is my first app.

Line 31 you declare the parsedUserGuess variable, OK, but you also give it its value by parsing the text field at that point. This happens before the user has been able to type anything, so the result is just 1.
You need to perform the parseInt and assign that to parsedUserGuess after the user has enetered his guess - eg in the actionPerformed method.

ps That code is really not bad for a first app. You are on the right track!

Edited 1 Year Ago by JamesCherrill

 if(parseduserguess > numberToGuess){
                    result.setText("Number too high!");
                }else if(parseduserguess < numberToGuess){
                    result.setText("Number too low");
                }

if you think something like this is not working (which in your case would mean that the actionPerformed wouldn't run. (or maybe, that parseduserguess == numberToGuess,

just add a simple print statement right before the if statement, printing both the values. it's a very basic form of debugging (and much easier compared to working with an actual debugging tool if you're just starting) which might tell you immediately what is going wrong.

i rearranged it a bit.seems to work on my end.DOUBLE CHECK.
There is no need to eliminate "else". I just love it that way.

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 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");

        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(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        button.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e)
            {
                int numberToGuess = rand.nextInt(100);
                int parseduserguess =        Integer.parseInt(userguess.getText());
                if(parseduserguess > numberToGuess)
                {
                    result.setText("Number too high!numberToGuess: " + numberToGuess );


                }
                if(parseduserguess < numberToGuess)
                {
                    result.setText("Number too low!numberToGuess:  "+ numberToGuess);
                }
            }
        });
    }
    }

Edited 1 Year Ago by Heanre: explanation

OK - maybe you want to have some kind of response to the user when the guess is right? Maybe you don't want the change the random number every time he guesses - seems it a bit unfair!

ps:
That actionListener code is how we did things before Java 8. It works, but the syntax was horrible and confusing and error prone - you start a method call on line 38 and don't finish it until line 55, and even then it ends with }}});

Now there's a much simpler way that looks like this:
First, put the code to handle your button click in its own method, eg

public void buttonClicked(ActioneEvent e) {
   // code just like your actionPeformed
}

then add that to the button by

button.addActionListner(this::buttonClicked);

If you have multiple buttons then just give each its own method.

Greetings shayan_doust!
Seems like people have given you the solution, but for future reference, try using the debugger tools (if you haven't already) to try to isolate the issue. :)

You already took the first step in isolating where the issue could be:

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."

The next step is to place breakpoints at the areas where you think the problem is (i.e. - near the actionListener), and then step through the application. Watch your variables, like "parseduserguess", and see what the results are. This will help you figure out what's going on. :)

Tekkno

This article has been dead for over six months. Start a new discussion instead.