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.getMessage());
continue;
} catch (ArithmeticException ae) {
System.err.println("Height can't be less than or equal to zero!");
continue;
}
}
// try-catch not necessary; we only get here when our input is valid
// we have to close the input connection to the user
scan.close();
return w / (h * h);
}
}
scan.close()
, it closes the underlying stream (System.in
), so you can't re-create a scanner onSystem.in
after that. You need to create the scanner in main and pass it on to your input function, closing it only once in your program. Haven't done Java in ages, but thatArithmeticException
makes me cringe. Don't use exceptions for control flow. \$\endgroup\$