I’d like to start off by saying that I’m a complete beginner when it comes to Java. What I know so far is what I’ve learn from my software development class at university. I’ve been messing about with it on my own and I managed to create an app which takes two doubles as inputs and calculates the BMI (body mass index) of the user.
This program works fine and does exactly what I want it to do however, if the user doesn’t enter anything and presses enter, then an exception is thrown. If the user enters anything but a number, an exception is thrown. When an exception is thrown the program is stopped. I would like to stop these exceptions from stopping the program completely and instead, return the user to the input stage and present an error message.
I have an idea of how it’s done. Some people have suggested using the try {..} catch (..) {..} construct and I have tried but I’ve always managed to break the program.
Anyone have any ideas?
So, here’s the code I have so far, sorry if there’s anything wrong, I’ve tried to add comments to make it easier.
import java.io.*;
public class bmi {
public static void main(String[] args) throws IOException {
/**
* User input of weight and height.
*/
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter how much you weigh in KG.");
double weight = Double.parseDouble(in.readLine()); //take weight input as double
System.out.println("Please enter how tall you are in meters.");
double height = Double.parseDouble(in.readLine()); //take height input as double
/**
* BMI calculation
*/
double bmi = weight / Math.pow(height,2); // weight divided by height squared
/**
* if else statements to find if person is underweight, at a healthy weight or overweight.
*/
if (bmi<18.5) { //if BMI is smaller than 18.5
System.out.println("Your BMI is " + bmi + ", you are underweight.");
}
else if (bmi>=18.5 && bmi<=25) { //if BMI is bigger than or equal to 18.5 and smaller than or equal to 25
System.out.println("Your BMI is " + bmi + ", you are at a healthy weight.");
}
else if (bmi>25) { //if bmi is bigger than 25
System.out.println("Your BMI is " + bmi + ", you are overweight");
}
}
}
Thanks.
You can use
Scannerfor that.Scannerprovides various methods to check appropriate types so you can use them. And there is no need to catch exceptions likeNumberFormatException