我在if else语句中分配字符串有麻烦 [英] I having trouble assigning strings in an if else statement

查看:66
本文介绍了我在if else语句中分配字符串有麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一个编程任务来计算bmi(体重指数)并将其分配给分类。根据bmi,它的分配如下。我在获取字符串的分类方面遇到麻烦。当我尝试将分类放入消息框中时,它告诉我我没有对其进行初始化。

Right now I have a programming assignment to calculate bmi(body mass index) and assign it to a classificaiton. Depending on the bmi it assigns it as follows. I am having trouble with the classification getting the strings. When i try to put the classification in a message box it tells me I do not have it initialized.

            public static void main(String[] args) {
    //Variables
    double bmi;         // Body Mass Index
    String weight;      // Weight in kilograms
    String height;      // height in meters
    String classification;

    weight = JOptionPane.showInputDialog("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
    double weight2 = Double.parseDouble(weight);
    height = JOptionPane.showInputDialog("Enter height in meters");
    double height2 = Double.parseDouble(height);

    bmi = weight2/(height2*height2);

    JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);

    if (bmi < 18.5)
    {
        classification = "Underweight";
    }
    else if (bmi < 25)
    {
        classification = "Normal";
    }
    else if (bmi < 30)
    {
        classification = "Overweight";
    }
    else
    {
        classification = "Obese";
    }


    JOptionPane.showInternalMessageDialog(null, "Your classification is: " + classification);


推荐答案

这不是您问题的真正答案,但您在if语句中缺少一些值。例如,如果bmi为24.95,那将不会输入正常或超重块。

It's not really an answer to your question, but you're missing some values in your if statements. For example, what if bmi was 24.95, that wouldn't enter either the Normal or Overweight blocks.

通常,我尝试选择一种比较类型,然后使用它。

In general, I try to pick one type of comparison, and just use that.

if (bmi < 18.5)
{
    classification = "Underweight";
}
else if (bmi < 25)
{
    classification = "Normal";
}
else if (bmi < 30)
{
    classification = "Overweight";
}
else
{
    classification = "Obese";
}

对于所得到的错误,假设在类别的正上方声明了分类if语句,实际上不应该给您该错误。

As for the error you're getting, assuming classification is declared just above the if statement, it really shouldn't be giving you that error.

这篇关于我在if else语句中分配字符串有麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆