gpt4 book ai didi

java - 我希望我的程序在用户输入整数以外的任何内容时显示错误消息并将其循环回来

转载 作者:行者123 更新时间:2023-12-02 04:20:36 26 4
gpt4 key购买 nike

我正在为我的 CS 类(class)做一个项目,并且一切都已完成,除了当用户在我询问他们的高度时输入任何不是整数的内容时,它会给出错误。我不知道如何捕获异常。这是我的源代码的片段。我是初学者,非常感谢您的帮助。

    JOptionPane.showMessageDialog (null, "This program calculates tidal volume.", "Tidal Volume Calculator", JOptionPane.INFORMATION_MESSAGE);
name = JOptionPane.showInputDialog("What is your name?");

while (flag3 == true)
{
sex = JOptionPane.showInputDialog("What is your sex?");

if(sex.equalsIgnoreCase("male") || sex.equalsIgnoreCase("m"))
{
while (flag2 == 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)
{
malePbwInch = 50 + 2.3 * (height - 60);
JOptionPane.showMessageDialog(null, name + "'s predicted body weight is: " + malePbwInch);
flag2 = false;
flag3 = false;
}
if(height <= 213 && height >= 114)
{
malePbwCm = 50 + .91 * (height - 152.4);
JOptionPane.showMessageDialog(null, name + "'s predicted body weight is: " + malePbwCm);
flag2 = false;
flag3 = false;
}
if(height > 84 && height < 114 || height < 48 || height > 213)
{
JOptionPane.showMessageDialog(null, "Invalid height. Please try again.");
}
else
{
try
{
malePbwInch = Integer.parseInt(height);
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Invalid height. Please try again.");
}
}

}
}

最佳答案

您正在将输入解析为整数,可能会发生异常。解析 try block 内的输入,并在 catch 中显示消息以输入数字。

关于java - 我希望我的程序在用户输入整数以外的任何内容时显示错误消息并将其循环回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812546/

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