当我输入母亲身高和父亲身高时,他们将计算孩子的身高。但是我如何添加一个循环,所以当孩子的高度为零或更低时,应该给出一个错误消息并重试?
import java.util.Scanner;
public class estimateHeight {
private static Scanner kb = new Scanner(System.in);
private static Scanner kbNum = new Scanner(System.in);
public static void calculateHeight(char gender, float motherHeight, float fatherHeight ) {
float height = 0;
if(gender == 'm' || gender == 'M')
height = ((motherHeight * 13/12) + fatherHeight )/2;
else
height = ((fatherHeight * 12/13) + motherHeight)/2;
if(height <= 0) {
System.out.println("Invalid inputs, please reneter: " );
calculateHeight(gender, motherHeight, fatherHeight);
}
else
System.out.println("The child's height is: " + height);
}
public static void main(String[] args) {
System.out.println("Estimating the Adult Height of a Child. Press Q or -1 to quit.\n");
String genderSelect;
float fatherHeight, motherHeight;
System.out.print("Gender? (m/f): ");
genderSelect = kb.nextLine();
if(genderSelect.equalsIgnoreCase("q"))
System.exit(0);
while(!(genderSelect.equalsIgnoreCase("m") || genderSelect.equalsIgnoreCase("f"))) {
System.out.print("Invalid. Gender? (m/f): ");
genderSelect = kb.nextLine();
}
System.out.print("Father's height? ");
fatherHeight = kbNum.nextFloat();
if(fatherHeight == -1)
System.exit(0);
System.out.print("Mother's height? ");
motherHeight = kbNum.nextFloat();
if(motherHeight == -1)
System.exit(0);
calculateHeight(genderSelect.charAt(0), motherHeight, fatherHeight);
}
}