KiwiNinja
KiwiNinja

Reputation: 63

Java: If statement not working?

Awnsers below worked, thanks guys!

boolean Again = true;
while (Again = true) 
{
    String input = JOptionPane.showInputDialog(null, "Input Za Number");
    try 
    {
        int input2 = Integer.parseInt(input);
        int R1 = 1;
        int R2 = 1;
        while (R2 < input2)
        {
            R1 = R1 * 2;
            R2 = R2 + 1;
            JOptionPane.showMessageDialog(null, R1);
        }
        String Ag = JOptionPane.showInputDialog(null, "Do it again? (Y/N)");
        if (Ag.equals("N"))
        {
            Again = false;
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, "What is  '" + input + "'?!?! Enter an actual number.");  
    }
}

I put the part thats not working as I hope in bold. Its the "if (Ag.equals("N"))". Im trying to make it so if a user inputs "N", then the program will stop running. Otherwise it will loop and keep going. Problem is, even if I type N, it will loop. I am getting no errors. Please help, I am much confuse :(

Upvotes: 1

Views: 1765

Answers (2)

Matt Clark
Matt Clark

Reputation: 28589

This is a prime example as to why professional developers will always use

if ( null == object )

over

if ( object == null )

In the event of a mistype, such as the following

// as posted
while ( Again = true ) // works, always true

// the other way
while ( true = Again ) // compiler error

the way as posted would be reassigning the value true to Again every time the loop is reiterated; if the statement had been written the other way, the compiler would have thrown an error, stating that you can not assign a value to true.

With just the single equals, you are reassigning the value of Again to true every time you get here, where as the double equals checks for equality.

In a case such as this, you really don't even need the true, you could simply be using

while ( Again )
// or again
while ( true == Again )

relevant

Upvotes: 4

When you do something like

while (Again = true) 

you are actually assigning the variable to true,

that is making your while infinite...


Do instead

 while (Again)  // since is boolean you dont need to compare against a true value..

Upvotes: 2

Related Questions