Reputation:
I wrote a bmi calculator program and I want to validate user input so that the user would not enter a negative number for the height or weight input.
How do I do this? I am new to Java, so I have no idea.
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) throws Exception {
calculateBMI();
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = s.nextFloat();
System.out.print("Please enter your height in cm: ");
float height = s.nextFloat();
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
private static void printBMICategory(float bmi) {
if(bmi < 24) {
System.out.println("You are underweight");
}else if (bmi < 29) {
System.out.println("You are healthy");
}else if (bmi < 34) {
System.out.println("You are overweight");
}else {
System.out.println("You are OBESE");
}
}
}
Upvotes: 2
Views: 428
Reputation: 330
Just to handle negative
inputs and keep asking for valid input,
boolean flag = true;
while(flag){
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}
To handle all the unexpected
inputs and keep asking for valid input,
boolean flag = true;
while(flag){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}catch(Exception e){
System.out.println("Invalid Input");
}
}
Upvotes: 1
Reputation: 18592
you can keep asking for value until the user input a valid number
private float readZeroOrPositiveFloat(Scanner scanner , String promptMessage)
{
float value = -1;
while(value < 0){
System.out.println(promptMessage);
value = scanner.nextFloat();
}
return value;
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = readZeroOrPositiveFloat(s , "Please enter your weight in kg: ");
float height = readZeroOrPositiveFloat(s , "Please enter your height in cm: ");
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
Upvotes: 2
Reputation: 15
When you get input from the scanner, you could use an if statement to make sure the value is not negative. For example:
if(input value <= 0){
System.out.println("Invalid Input");
}else { *program continues* }
Upvotes: 0