HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Calculating the ideal body weight

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
idealtheweightcalculatingbody

Problem

The following question was taken from Absolute Java 5th ed. by Walter Savitch:


A simple rule to estimate your ideal body weight is to allow 110 pounds for the first 5 feet of height and 5 pounds for each additional inch. Write a program with a variable for the height of a person in feet and another variable for the additional inches. Assume the person is at least 5 feet tall. For example, a person that is 6 feet and 3 inches tall would be represented with a variable that stores the number 6 and another variable that stores the number 3. Based on these values, calculate and output the ideal body weight.

This is the code that I have written:

public class Question9 {

    private static final int INCH_PER_FEET = 12;
    private static final int POUND_PER_INCH = 5;
    private static final int MIN_HEIGHT_FEET = 5;
    private static final int MIN_WEIGHT_POUND = 110;

    public static void main(String[] args) {

        int feet = 6;
        int inches = 3;

        System.out.println(idealBodyWeight(feet, inches) + " pounds");
    }

    private static int idealBodyWeight(int feet, int inches) {
        int pounds = MIN_WEIGHT_POUND;

        if ((feet > MIN_HEIGHT_FEET)) {

            inches += (feet - MIN_HEIGHT_FEET) * INCH_PER_FEET;
        }

        pounds += inches * POUND_PER_INCH;

        return pounds;
    }
}

Solution

There isn't really all that much to say, your code is generally good.

  • Declare variables where they are needed: you do not use pounds in the if statement, so I would remove it and just use MIN_WEIGHT_POUND in the return directly. Alternatively, you could move the declaration of pounds to after the if.



  • Try to minimize white space: It's good to sort code by using newlines, but too much isn't good either. remove the newline after the if statement, and maybe some more.



  • Try to minimize use of brackets: No need to wrap the boolean expression in brackets.



With these changes, your code would look like this:

private static int idealBodyWeight(int feet, int inches) {
    if (feet > MIN_HEIGHT_FEET) {
        inches += (feet - MIN_HEIGHT_FEET) * INCH_PER_FEET;
    }
    return MIN_WEIGHT_POUND + inches * POUND_PER_INCH;
}

Code Snippets

private static int idealBodyWeight(int feet, int inches) {
    if (feet > MIN_HEIGHT_FEET) {
        inches += (feet - MIN_HEIGHT_FEET) * INCH_PER_FEET;
    }
    return MIN_WEIGHT_POUND + inches * POUND_PER_INCH;
}

Context

StackExchange Code Review Q#62820, answer score: 5

Revisions (0)

No revisions yet.