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

Simple BMI calculator in Java

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

Problem

A similar question must have been asked a thousand times, but for the life of me I can't figure this out. I am new to Java and I want to create a programme that asks a user for his or her height and weight, and calculate the corresponding BMI. I want to throw exceptions for the wrong input (has to be a double, non-negative and not zero) and I want to catch any mathematical errors that may occur. The follow code does that, but I have exact duplication for handling the input of height and weight. How can I simplify this into a more concise format without losing any functionality?

```
import java.util.InputMismatchException;
import java.util.Scanner;

public class BMIcalculator {
public static void main(String[] args){
double BMI = calculateBMI();
System.out.print("\nYour BMI is " + BMI + ".");
}

public static double calculateBMI() {
// Scanner allows us to request a users input
Scanner scan = new Scanner(System.in);
// Initialize doubles as zero values
double w=0, h=0;

// Ask for user input (weight)
System.out.println("Please enter your weight");
while(true) {
try {
w = scan.nextDouble();
if (w <= 0) throw new ArithmeticException();
break;
} catch (InputMismatchException ime) {
System.err.println("Ahw, error: " + ime.getMessage());
continue;
} catch (ArithmeticException ae) {
System.err.println("Weight can't be less than or equal to zero!");
continue;
}
}
// Ask for user input (height)
System.out.println("Please enter your height");
while(true) {
try {
h = scan.nextDouble();
if (h <= 0) throw new ArithmeticException();
break;
} catch (InputMismatchException ime) {
System.err.println("Ahw, error: " + ime.getM

Solution

Avoiding code repetition

As pointed out in some of the other answers, getting a double value from the keyboard can be abstracted into its own method to avoid code repetition:

private static double getDouble(Scanner scanner, String metric) {
    System.out.println("Enter " + metric);
    double result;
    while (!scanner.hasNextDouble() || (result = scanner.nextDouble()) <= 0) {
        System.out.println(metric + " must be a positive number.");
        scanner.next();
    }
    return result;
}


try-with-resources

If you are on Java 7 and above, you should use try-with-resources for efficient handling of the underlying I/O resource:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        double weight = getDouble(scanner, "Weight (kg)");
        double height = getDouble(scanner, "Height (m)");
        System.out.println("Your BMI is: " + /* calculation */);
    }
}


Units

It's important to note that BMI is expressed in units of \$\frac{kg}{m^2}\$, so you should definitely display the units of measurement too. Otherwise, you'll need extra methods to perform the conversion to kilograms and meters. :)

Comments

Simply put, comments should explain the why, not how. Most of your comments now are just descriptive, i.e. on the how, which is already apparent in the code. Comments are sometimes seen as redundant as they are prone to being outdated. Therefore, comment sparingly, and only when you really need it to explain something that is non-obvious. Even so, try to make the code 'obvious' first. :)

Code Snippets

private static double getDouble(Scanner scanner, String metric) {
    System.out.println("Enter " + metric);
    double result;
    while (!scanner.hasNextDouble() || (result = scanner.nextDouble()) <= 0) {
        System.out.println(metric + " must be a positive number.");
        scanner.next();
    }
    return result;
}
public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        double weight = getDouble(scanner, "Weight (kg)");
        double height = getDouble(scanner, "Height (m)");
        System.out.println("Your BMI is: " + /* calculation */);
    }
}

Context

StackExchange Code Review Q#108776, answer score: 5

Revisions (0)

No revisions yet.