Skip to content

Instantly share code, notes, and snippets.

@ParadauxIO
Created October 19, 2020 12:44
Show Gist options
  • Save ParadauxIO/5709c2723a546a334202c63dcc6cf886 to your computer and use it in GitHub Desktop.
Save ParadauxIO/5709c2723a546a334202c63dcc6cf886 to your computer and use it in GitHub Desktop.
Calculate a user's BMI when prompted for their weight and height.
import java.util.InputMismatchException;
import java.util.Scanner;
public class BMI {
static double userWeight; // Given to the nearest kilogram
static double userHeight; // Given in meters
static float userBMI; //
/**
* Calculate the user's BMI via
* @param args Unused for the purposes of this program.
* */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your weight in kg? ");
try {
userWeight = scanner.nextDouble();
} catch (InputMismatchException exception) {
System.out.print("The weight retrieved does not match the pattern for the primitive int.");
return;
}
System.out.print("What is your height in metres?");
try {
userHeight = scanner.nextDouble();
} catch (InputMismatchException exception) {
System.out.print("The height retrieved does not match the pattern for double.");
return;
}
scanner.close();
try {
// The Definition of the BMI, or Body-Mass Index is defined as the user's weight, divided by the square of their height.
userBMI = (float) (userWeight / Math.pow(userHeight, 2));
} catch(ClassCastException exception) {
System.out.print("An unknown error occurred, please see the stack trace below.");
exception.printStackTrace();
return;
}
System.out.print("Your BMI is " + userBMI);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment