6
\$\begingroup\$

My task:

Body Mass Index (BMI) is a measure of health based on height and weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters.

Write a java code to let the user enter weight, feet, and inches and interpret the users BMI.

My code:

//import scanner
import java.util.Scanner;

//import Math class
import java.lang.Math;

public class ComputeBMI {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //create scanner
        Scanner input = new Scanner(System.in);

        //declare variables
        double weight;
        int feet;
        int inches;

        //prompt user
        System.out.print("Enter weight in pounds: ");
        weight = input.nextFloat();

        System.out.print("Enter feet: ");
        feet = input.nextInt();

        System.out.print("Enter inches: ");
        inches = input.nextInt();

        //convert measurements
        double weightInKilos = weight * 0.453592;
        double heightInMeters = (((feet * 12) + inches) * .0254);
        double bmi = weightInKilos / Math.pow(heightInMeters, 2.0);
//      double bmi = weightInKilos / (heightInMeters * heightInMeters);

        //display output
        System.out.println("Your BMI is: " + bmi);

        //interpret BMI
        if (bmi < 18.5 ) {
            System.out.print("Underweight");
        }

        else if (bmi >= 18.5 && bmi < 25) {
            System.out.print("Normal");
        }

        else if (bmi >= 25 && bmi < 30) {
            System.out.print("Overweight");
        }

        else if (bmi >= 30) {
            System.out.print("Obese");
        }

//      Do I need this last else if there?
//      else {
//          System.out.print("");
//      }

        input.close();

    }

}

I used only the material we've been taught thus far to complete my code. My POC is clarity/fluidity of my code and my variable data types. In my mind, feet and inches should be integers and weight should be a double. Valid hypothesis?

Thanks, y'all.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just about your last comment in code: you neither need the last else nor that much of comparison you make. In first if you check if bmi is smaller 18.5. So in the upcoming else case you don't have to check if its equal or bigger 18.5, if this would not be true it would be smaler so the if case had taken action and the else won't. \$\endgroup\$ Commented Mar 19, 2017 at 15:32

3 Answers 3

6
\$\begingroup\$
  1. You run all the computations in the main method. It's not a good practice. One method should do one focused thing. That's why I'd recommend to create a separate method for "step" of your computation:

    • converting measurements (something like double poundsToKilograms(double weightInPounds)
    • computing the BMI given the height and the weight of the user
    • converting a numeric value of the BMI to a human-readable message

    This way, you main method would just read the input, call these methods and print the result. It would make your code more readable and testable (you would be able to test your methods separately)

  2. The comments should explain what the code does and why it does what it does. They shouldn't describe how it works. That is, it's a good idea to create a doc comment for each method saying what it does, how it behaves if it gets an incorrect input and so on. Conversely, comments like //declare variables or //create scanner actually harm the readability. They just create noise. They don't add anything useful to the code itself. Writing self-documenting code is a good practice (that is, ideally it should be clear what your code does from the code itself).

  3. ComputeBMI doesn't sound like a good class name to me. I'd rather call it a BMICalculator (it's conventional to name classes with nouns and methods with verbs).

  4. The message Enter feet: looks kind of strange. I think it should say that it requests the user's height (it's not clear from the message itself).

  5. It's fine to keep the height as an int, but I would show a message to the user saying that. Otherwise, they may get an unexpected error.

  6. You could also add some kind of input validation and error handling so that your program doesn't fail with an exception (it might be confusing for the user) but rather prints a more suitable message and possible prompts the user again.

\$\endgroup\$
1
  • \$\begingroup\$ 1. We've only done so that way. Actually, I don't understand what exactly you're saying yet, unfortunately. 2. The comments are going to be removed in the final submission. 3. Good point, thank you. 4. I agree, however, it was the prompt in the sample output so I just went with it. 5. Good point, thank you. 6. I thought about this. I didn't know whether it'd bloat my simple project or not. Thanks again! \$\endgroup\$ Commented Mar 19, 2017 at 17:53
4
\$\begingroup\$

I'll go through your code from top to bottom:

//import scanner
import java.util.Scanner;

The comment "import scanner" is not necessary, since it only repeats what the code below already does.

//import Math class
import java.lang.Math;

This import can be removed completely, since all classes from java.lang are imported implicitly.

public class ComputeBMI {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

This "TODO" comment is something you have to remove. It makes your code look sloppy, as if you didn't proofread it yourself before showing it to other people.

        //create scanner
        Scanner input = new Scanner(System.in);

As a beginner, you may need these kinds of comments, but as soon as you have written this type of code five times, you should get rid of these comments.

        //declare variables
        double weight;
        int feet;
        int inches;

In Java, it is good practice to declare variables as late as possible, that is when they are first used.

        //prompt user
        System.out.print("Enter weight in pounds: ");
        weight = input.nextFloat();

This line should declare the weight variable: double weight = input.nextDouble();. I changed the method call to nextDouble so that it matches the type of the height variable.

        System.out.print("Enter feet: ");
        feet = input.nextInt();

        System.out.print("Enter inches: ");
        inches = input.nextInt();

        //convert measurements
        double weightInKilos = weight * 0.453592;
        double heightInMeters = (((feet * 12) + inches) * .0254);
        double bmi = weightInKilos / Math.pow(heightInMeters, 2.0);
//      double bmi = weightInKilos / (heightInMeters * heightInMeters);

You chose excellent names for your variables. When dealing with different measurement units, each variable should mention the unit, which you did here.

        //display output
        System.out.println("Your BMI is: " + bmi);

        //interpret BMI
        if (bmi < 18.5 ) {
            System.out.print("Underweight");
        }

        else if (bmi >= 18.5 && bmi < 25) {
            System.out.print("Normal");
        }

        else if (bmi >= 25 && bmi < 30) {
            System.out.print("Overweight");
        }

        else if (bmi >= 30) {
            System.out.print("Obese");
        }

//      Do I need this last else if there?
//      else {
//          System.out.print("");
//      }

No, you don't need the last else if. You can just write } else { System.out.println("Obese"); }.

Note the println instead of print. When printing something, you usually print it in lines. Each line should be terminated properly, which you do with println. The ln in println stands for linebreak.

        input.close();

    }

}

Altogether, a very nice piece of work. The many comments tell the reader that you are a beginner, but don't worry, in a few weeks you can remove them and still understand the program equally well.

\$\endgroup\$
3
\$\begingroup\$

Reading from the previous answer given by krasevich I too recommend you become familiar with using multiple methods rather than putting everything in the main method. Although you may not have learnt how to make other methods yet, it is a simple concept to learn and is easily found on numerous YouTube tutorials. Think of using methods as the a similar concept to paragraphing your writing. Sectioning pieces off makes it easier to understand, aids maintainability and debugging as well as makes parts of your code more re-usable.

I for example would would have a getInput methods to get the values for the user, a convertMeasurements method for converting the users input and finally a displayResult method.

In regards to commenting, yes some comments are somewhat pointless if what you're doing is pretty self explanatory. Perhaps multi-line comments would be more useful to give a general explanation to what certain sections of your code do?

Also Scanner has a tendency to throw errors if the value you are assigning isn't what it's expecting. In your example if the user inputs a String rather than an integer that will throw an error causing the program to terminate. So ideally you need so sort of validation or error handling in your program...perhaps a validation method that requests new input if an error is thrown? Remember, it's very easy to assume that users will never input silly things like words where numbers are meant to go but trust me...they will. It's best to handle those eventualities

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.