//Scanner
Scanner scan = new Scanner(System.in);
//Variables
double bmi; // Body Mass Index
double weight; // Weight in kilograms
double height; // Height in meters
String[] classification = {"Underweight", "Normal", "Overweight", "Obese"};
System.out.print("Your weight in KG \n");
weight = scan.nextDouble();
System.out.print("Enter height in meters: \n");
height = scan.nextDouble();
bmi = weight / (height * height);
if (bmi < 18.5) {
System.out.print("You're " + classification[0] + "\n");
} else if (bmi < 25) {
System.out.print("You're " + classification[1] + "\n");
} else if (bmi < 30) {
System.out.print("You're " + classification[2] + "\n");
} else {
System.out.print("You're " + classification[3] + "\n");
}
switch (Arrays.toString(classification)) {
case "Underweight":
System.out.println("Underweight");
break;
case "Normal":
System.out.println("Normal");
break;
case "Overweight":
System.out.println("A bit overweighted");
break;
case "Obese":
System.out.println("A bit obese");
break;
default:
System.out.println("Ok");
break;
}
}
输出,我的switch语句在if-else语句之后不起作用。它忽略所有内容,直接跳到我的交换机中的默认值。我的意图是在if-else之后再跟一些文字。因此,基本上,如果我的计算表明我超重了,那么现在我的switch语句必须跳转到“超重”情况并打印出那段代码。.我在做什么错?
答案 0 :(得分:3)
Arrays.toString(classification)
的结果为[体重不足,正常,体重超重,肥胖]与任何切换情况都不匹配。
解决方案可能是这样的:
String result = null;
if (bmi < 18.5) {
System.out.print("You're " + classification[0] + "\n");
result = classification[0];
} else if (bmi < 25) {
System.out.print("You're " + classification[1] + "\n");
result = classification[1];
} else if (bmi < 30) {
System.out.print("You're " + classification[2] + "\n");
result = classification[2];
} else {
System.out.print("You're " + classification[3] + "\n");
result = classification[3];
}
switch (result) {
case "Underweight":
System.out.println("Underweight");
break;
case "Normal":
System.out.println("Normal");
break;
case "Overweight":
System.out.println("A bit overweighted");
break;
case "Obese":
System.out.println("A bit obese");
break;
default:
System.out.println("Ok");
break;
}