gpt4 book ai didi

java - 为什么while循环一直循环

转载 作者:行者123 更新时间:2023-12-01 18:11:18 25 4
gpt4 key购买 nike

当我声明 flag false 时,为什么 while 循环继续循环?一旦我输入正确的输入,程序就应该结束。任何帮助将不胜感激。刚接触java。非常感谢大家!

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

}

最佳答案

即使是经验丰富的程序员也会时不时地犯这样的错误:您将 true 分配给 flag,因此条件始终为 true。您需要双等于比较运算符

while (flag == true)

或者只是

while (flag)

关于java - 为什么while循环一直循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com