Reputation: 19
Why does the while loop keep looping when I declare flag false? Once I enter a correct input, the program should end. Any help would be greatly appreciated. New to java. Many thanks everyone!
import javax.swing.JOptionPane;
import java.util.*;
public class Project1Chang
{
public static void main(String[] args)
{
String name;
String sex;
int height;
boolean flag = true;
JOptionPane.showMessageDialog (null, "This program calculates tidal volume.", "Tidal Volume Calculator", JOptionPane.INFORMATION_MESSAGE);
name = JOptionPane.showInputDialog("What is your name?");
sex = JOptionPane.showInputDialog("What is your sex?");
while (flag = true)
{
height = Integer.parseInt (JOptionPane.showInputDialog("What is your height? (48-84 inches or 114-213 centimeters) \nEnter whole numbers only."));
if (height <= 84 && height >= 48)
{
if (sex.equalsIgnoreCase("male") || sex.equalsIgnoreCase("m"))
{
double malePbwInch = 50 + 2.3 * (height - 60);
JOptionPane.showMessageDialog(null, malePbwInch);
flag = false;
}
}
else if (height <= 213 && height >= 114)
{
if (sex.equalsIgnoreCase("male") || sex.equalsIgnoreCase("m"))
{
double malePbwCm = 50 + .91 * (height - 152.4);
JOptionPane.showMessageDialog(null, malePbwCm);
flag = false;
}
}
else
{
JOptionPane.showMessageDialog(null, "This is an invalid input. Try again.");
}
}
}
}
Upvotes: 0
Views: 117
Reputation: 49
The = operator assigns the variable with a value. The == operator tests the variable for equality with another value.
The while loop never stops looping because the condition within the loop is always true. This is because you assigned the value of flag to true.
To allow termination of the loop, change while (flag = true)
to while (flag == true)
Upvotes: 0
Reputation: 505
As the previous posters already mentioned you'll have to use ==
instead of =
.
But the more elegant way of doing this would be to just write while(flag)
If you just have a boolean in a loop you don't have to check if it's ==true
or ==false
since the boolean itself contains the values true
or false
!
Upvotes: 1
Reputation: 306
Even experienced programmers make this mistake from time to time: You are assigning true to flag, so the condition is always true. You need the double-equals comparison operator
while (flag == true)
or really just
while (flag)
Upvotes: 2
Reputation: 440
flag = true should be flag == true
flag = true assigns true to flag and returns true to the while loop
Upvotes: 0