user2802785
user2802785

Reputation: 109

nested if else logic error in Java

I'm doing the Guessing Game for Java homework and I am having a logic problem with the nested if else. I am trying to determine two things: is the number to high/low, and if the user is getting hotter/colder. I have a variables intGuess and intOldGuess. I am trying to compare the two for the hotter/colder but I either end up with intOldGuess being 0, or the same as intGuess when it comes time for comparison. Neither are correct of course. Here is what I have so far:

Here is the section I think is giving me trouble:

public void actionPerformed(ActionEvent e)
        {
            int intGuess = 0, intOldGuess;
            intOldGuess = intGuess;

            try
            {
                intGuess = Integer.parseInt(txaUserGuess.getText().trim());

                if (intGuess < intRandomNum)
                {
                    lblHighLow.setText("Too Low");

                    if (intGuess > intOldGuess)
                    {
                        lblHotCold.setText("Getting Colder");
                        System.out.println(intOldGuess);
                        System.out.println(intGuess);
                    } 

Here is the entire code if you need it:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class GuessNumber extends JFrame
{
    private JTextField txaUserGuess;
    private JLabel lblStart, lblPrompt, lblHighLow, lblHotCold;
    private JButton btnGuess, btnQuit, btnAgain;

    private int intRandomNum;

    Container c = getContentPane();

    public static void main(String args[])
    {
        GuessNumber app = new GuessNumber();

    }

    public GuessNumber()
    {
        super("Guessing Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Creates components
        btnGuess = new JButton("Guess");
        btnQuit = new JButton("Quit");
        btnAgain = new JButton("Play Again?");
        lblStart = new JLabel("I have a number between 1 and 1000.");
        lblPrompt = new JLabel(
                "Can you guess my number? Please enter your guess:");

        lblHighLow = new JLabel("");
        lblHotCold = new JLabel("");
        txaUserGuess = new JTextField(5);

        setLayout(new FlowLayout());

        c.add(lblStart);
        c.add(lblPrompt);
        c.add(txaUserGuess);
        c.add(btnGuess);
        c.add(btnQuit);
        c.add(btnAgain);
        c.add(lblHighLow);
        c.add(lblHotCold);

        setSize(350, 200);
        setVisible(true);
        btnAgain.setVisible(false);

        RandomNumber();

        FirstGuessButtonHandler ghandler = new FirstGuessButtonHandler();
        btnGuess.addActionListener(ghandler);

        QuitButtonHandler qhandler = new QuitButtonHandler();
        btnQuit.addActionListener(qhandler);

        AgainButtonHandler ahandler = new AgainButtonHandler();
        btnAgain.addActionListener(ahandler);

    }

    private void RandomNumber()
    {
        intRandomNum = new Random().nextInt(1000) + 1;
        System.out.println(intRandomNum);
    }

    class QuitButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }

    class AgainButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {

        }
    }

    class FirstGuessButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            int intGuess = 0, intOldGuess;
            intOldGuess = intGuess;

            try
            {
                intGuess = Integer.parseInt(txaUserGuess.getText().trim());

                if (intGuess < intRandomNum)
                {
                    lblHighLow.setText("Too Low");

                    if (intGuess > intOldGuess)
                    {
                        lblHotCold.setText("Getting Colder");
                        System.out.println(intOldGuess);
                        System.out.println(intGuess);
                    } else if (intGuess < intOldGuess)
                    {
                        lblHotCold.setText("Getting Hotter");
                    }

                } else if (intGuess > intRandomNum)
                {
                    lblHighLow.setText("Too High");
                } else
                {
                    c.setBackground(Color.GREEN);
                    lblHighLow.setText("\n\tCorrect!");
                    txaUserGuess.setEditable(false);
                    btnAgain.setVisible(true);
                    btnGuess.setEnabled(false);
                }

            } catch (NumberFormatException e1)
            {
                lblHighLow.setText("\n\tEnter a VALID number!");
            }
        }

    }

}

Upvotes: 0

Views: 555

Answers (6)

Prasad
Prasad

Reputation: 1188

Use of local variables should be avoided, if you want to use them without re-initialization. To retain the value of variables make those variables Reference variable.

You can do this-

class ClassName{
     int oldguess;
     public void yourMethod(){
           int newGuess = 0;

Upvotes: 1

djna
djna

Reputation: 55907

The problem lies with how you are keeping state

 int intGuess = 0, intOldGuess;
 intOldGuess = intGuess;

Here you are declaring local variables, which are recreated each time your function is called.

Upvotes: 0

Xandaros
Xandaros

Reputation: 655

if (intGuess < intRandomNum)
    {
        lblHighLow.setText("Too Low");

        if (intGuess > intOldGuess)
        {
            lblHotCold.setText("Getting Colder");
            System.out.println(intOldGuess);
            System.out.println(intGuess);
        }

The problem is, that you have the second if nested in the first. The second only ever gets checked, if the first is valid. The second condition can therefore never be true. (It only checks if intGuess is greater than inOldGuess, if intGuess is less than intOldGuess, which can never be.

You need to take the second if out of the first.

Also, you seem to want to store data in intOldGuess, but you declared it as a local variable. You need to set it is a field if you want it to store data between method calls.

Upvotes: 0

user2403009
user2403009

Reputation:

int intGuess = 0, intOldGuess;

is currently contained in the method actionPerformed() these need to be declared as fields (outside methods but in the class body).

Also you may consider writing those as

int intGuess = 0;
int intOldGuess;

for clarity sake (it looks cleaner and will make your code more easily readable)

Upvotes: 2

FazoM
FazoM

Reputation: 4956

In this place here:

int intGuess = 0, intOldGuess;
intOldGuess = intGuess;

You are defining intOldGuess, but in second line you assign value 0 to it. You probably should keep this variable in class scope and don't assign 0 to it.

Upvotes: 2

sanbhat
sanbhat

Reputation: 17622

intOldGuess is local variable to the method. So every time the method gets called, it gets initialized to 0 (default value).

To preserve the value, you might want to create the variable as class field

class FirstGuessButtonHandler implements ActionListener
 {
        int intOldGuess;

        public void actionPerformed(ActionEvent e)
        {
            int intGuess = 0;

But remember, in above case, you need to maintain the same instance of FirstGuessButtonHandler class, since the class fields are maintained per instance of the class.

Other approach could be to create intOldGuess as static class field too

Upvotes: 2

Related Questions