一般来说,我是一个新程序员,所以如果这个问题有点基础,请原谅我。
该程序的目标是“最佳体重”的简单计算,并在运行时不断抛出异常,超过第 35 行中的 a 和 b 字符串比较。我尝试删除逻辑运算符,但这似乎仍然不是问题. 我哪里错了?
import java.util.*;
public class WeightCalc {
//Initialize variables
static int feet = 0, inches = 0, totalWeight = 0;
static boolean isMale;
public static void optimalWeight(){
// Calculate optimal weight
if (isMale == true){
if (feet >= 5){
totalWeight = 106 + 6*(inches);
} else{
System.out.print("Error, you're a midget.");
}
}
if (isMale == false){
if (feet >= 5){
totalWeight = 100 + 5*(inches);
} else{
System.out.print("Error, you're a midget.");
}
}
}
public static void main(String[] args){
String a = "Male", b = "male";
// Initialize kboard Scanner
Scanner kboard = new Scanner(System.in);
// Ask for gender and assign isMale
System.out.println("What is your gender? ");
String gender = kboard.nextLine();
if (gender.equals(a) || gender.equals(b)){
isMale = true;
}else {
isMale = false;
}
// Ask for height, first feet, then inches
System.out.println("What is your height in regards to feet? ");
kboard.nextInt(feet);
System.out.println("What is your remaining h eight in inches? ");
kboard.nextInt(inches);
//Call optimalWeight method and run
optimalWeight();
// Print the output
System.out.println("Your optimal weight should be " + totalWeight + ".");
// Set isMale opposite to what it was before and calculate opposite sex's potential weight
isMale = !isMale;
optimalWeight();
// Print the output of the second run
System.out.println("If you were of the opposite sex, your weight would be " + totalWeight + ".");
// Close the Scanner variable
kboard.close();
}
}