简体   繁体   English

Java IF-ELSE IF-ELSE 跳过 if 和 else if 检查并自动打印出 else 语句

[英]Java IF-ELSE IF-ELSE skipping the if and else if check and prints out else statement automatically

Java 11.6 In this BMI calculator that will take in Person's weight, height and calculate the BMI. Java 11.6 在这个 BMI 计算器中,它将计算人的体重、身高并计算 BMI。 The BMI is calculated properly however in the classify BMI method the program skips the if and else if check and just prints out the else statement which is "obese" for every test. BMI 计算正确,但是在分类 BMI 方法中,程序跳过if 和 else if检查,只打印出每次测试“肥胖”的 else 语句。 Is the loop implemented incorrectly?循环执行不正确吗? or the value of BMI is not initiating in the loop.或者 BMI 的值不在循环中启动。 When I print out the BMI, I do see that for every test the BMI does change so that is not a problem.当我打印出 BMI 时,我确实看到每次测试的 BMI 都会发生变化,因此这不是问题。

The PersonWeight.java class PersonWeight.java 类

import java.time.Year;


public class PersonWeight {


    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }



    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }



    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }



}

The test class that has the main method具有 main 方法的测试类

import java.util.Scanner;
public class TestPersonWeight {



    public static void classifyBMI() {
        PersonWeight PersonWeight = new PersonWeight();
        double bmi = PersonWeight.ComputeBMI();


        if(bmi<18.5) {
            System.out.printf("Underweight");

        }else if (bmi >= 18.5 && bmi<25) {
            System.out.printf("Normal Weight");
        }else if (bmi >=25 && bmi<30) {
            System.out.printf("Overweight");
        }else  {
            System.out.printf("Obese");

        }
    }

        public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);


        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

        PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
        classifyBMI();

    }
}

Your classifyBMI() method creates a new PersonWeight where the height and weight remain 0.0 , so you are dividing 0.0 by 0.0 , which results in NaN .您的classifyBMI() PersonWeight classifyBMI()方法创建了一个新的PersonWeight ,其中身高和体重保持为0.0 ,因此您将0.0除以0.0 ,结果为NaN Hence, none of the comparisons evaluates to true , and you end up with the else clause being executed.因此,所有比较的计算结果都不是true ,最终会执行 else 子句。

You should change that method to be an instance method (ie not static ), and call it for the PersonWeight instance that you create in your main method.您应该将该方法更改为实例方法(即不是static ),并为您在main方法中创建的PersonWeight实例调用它。

Or, as an alternative, keep that method static , but pass to it the previously calculated bmi value.或者,作为替代方法,保持该方法static ,但将先前计算的bmi值传递给它。

ie in your main write:即在你的main写作中:

double bmi = PersonWeight.ComputeBMI();
System.out.printf("%n Height: " + PersonWeight.getHeight());
System.out.printf("%n Weight: " + PersonWeight.getWeight());
System.out.printf("%n BMI: " + bmi);
classifyBMI(bmi);

and classifyBMI will become:并将classifyBMI为:

public static void classifyBMI (double bmi) {
    if(bmi < 18.5) {
        System.out.printf("Underweight");
    } else if (bmi >= 18.5 && bmi < 25) {
        System.out.printf("Normal Weight");
    } else if (bmi >= 25 && bmi < 30) {
        System.out.printf("Overweight");
    } else {
        System.out.printf("Obese");
    }
}

PS using the same identifier - PersonWeight - for both your class name and the variable name is a bad practice. PS 对您的类名和变量名使用相同的标识符 - PersonWeight - 是一种不好的做法。 Use personWeight for the variable.使用personWeight作为变量。

The error is here:错误在这里:

PersonWeight personWeight = new PersonWeight();
double bmi = personWeight.computeBMI();

This always returns NaN (Not a number) because you compute on a fresh new object which has only zeroes in it.这总是返回 NaN(不是数字),因为您在一个只有零的新对象上进行计算。 Division by zero is not allowed, hence the result is NaN.不允许被零除,因此结果为 NaN。 All if-comparisons fail because NaN cannot be compared to any number.所有 if 比较都失败,因为 NaN 无法与任何数字进行比较。

Solution 1: Move the ``classifyBMI() method inside the PersonWeight``` class and use the current class instance attributes (now a new class with zeroes) for the calculation.解决方案 1: method inside the PersonWeight 类中移动 ``classifyBMI() method inside the并使用当前类实例属性(现在是一个带有零的新类)进行计算。

Solution 2: Pass the filled PersonWeight``` instance to the classifyBMI()``` method as an argument and use that for the calculation.解决方案2:将填充的PersonWeight``` instance to the作为参数传递PersonWeight``` instance to the classifyBMI()``` 方法,并将其用于计算。

Solution 3: Pass the bmi value to the ``classifyBMI()``` method as an argument and use that for the calculation.解决方案 3:将bmi值作为参数传递给 ``classifyBMI()``` 方法,并将其用于计算。

The following code demonstrates all three solutions:以下代码演示了所有三种解决方案:

import java.util.Scanner;

public class Main
{

    public static class PersonWeight
    {
        private double height;
        private double weight;

        public PersonWeight()
        {
            height = 0;
            weight = 0;
        }

        public void setHeight(double h)
        {
            this.height = h;
        }

        public double getHeight()
        {
            return height;
        }

        public void setWeight(double w)
        {
            this.weight = w;
        }

        public double getWeight()
        {
            return weight;
        }

        public double computeBMI()
        {
            double bmi = ((weight) / (height * height));
            return bmi;
        }

        private void classifyBMI1()
        {
            double bmi = ((weight) / (height * height));

            if (bmi < 18.5)
            {
                System.out.println("Underweight");
            }
            else if (bmi >= 18.5 && bmi < 25)
            {
                System.out.println("Normal Weight");
            }
            else if (bmi >= 25 && bmi < 30)
            {
                System.out.println("Overweight");
            }
            else
            {
                System.out.println("Obese");
            }
        }
    }

    private static void classifyBMI2(PersonWeight personWeight)
    {
        double bmi = personWeight.computeBMI();
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    private static void classifyBMI3(double bmi)
    {
        if (bmi < 18.5)
        {
            System.out.println("Underweight");
        }
        else if (bmi >= 18.5 && bmi < 25)
        {
            System.out.println("Normal Weight");
        }
        else if (bmi >= 25 && bmi < 30)
        {
            System.out.println("Overweight");
        }
        else
        {
            System.out.println("Obese");
        }
    }

    public static void main(String[] args) throws Exception
    {
        Scanner input = new Scanner(System.in);
        PersonWeight personWeight = new PersonWeight();

        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        personWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        personWeight.setWeight(w);

        System.out.printf("%nHeight: %f%n", personWeight.getHeight());
        System.out.printf("Weight: %f%n", personWeight.getWeight());
        System.out.printf("BMI: %f2%n", personWeight.computeBMI());

        personWeight.classifyBMI1();
        classifyBMI2(personWeight);
        classifyBMI3(personWeight.computeBMI());
    }
}

I also fixed other things:我还修复了其他事情:

Variable names and method names should start with a small letter.变量名和方法名应该以小写字母开头。 Upper case beginnings are reserved for class name.为类名保留大写开头。 To print simple strings use println() instead of printf() for better performance.要打印简单的字符串,请使用println()而不是printf()以获得更好的性能。 When you use printf() to output variables, then use placeholders like %f instead of string concatenation.当您使用printf()输出变量时,请使用%f等占位符而不是字符串连接。 Again this provides better performance.这再次提供了更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM