这只是代码的一部分。所以出于某种原因,当我尝试运行它并且值在可接受的范围内时,我得到一个"无效的重量!"但是它不应该像其他声明那样做。
所以...我选择1作为我想要的选择,我应该在几个月内输入一个年龄和一个以kg为单位的重量。年龄必须在0到24个月之间。重量必须在2到15公斤之间。
If weight(kg) >= (age(months))/3 + 2 and
weight(kg) <= (5*age(months))/12 + 5...
我想打印出#34;健康&#34;如果没有这个范围 - 不健康。
System.out.println("(1) months then weight in kg");
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int selection = input.nextInt();
switch(selection){
case 1:
System.out.println("Enter age in months: ");
double month = input.nextDouble();
if(month >= 0 && month <= 24){
System.out.println("Enter a weight in kg: ");
} else{
System.out.println("Not a baby anymore");
System.exit(0);
}
double weight = input.nextInt();
if(weight >= 2 && weight <= 15 && weight >= (month/3) +2 && weight <= ((5 * month)/12) +5) {
System.out.println("Healthy!");
} else if(weight <= (month/3) +2 && weight >= ((5 * month)/12) +5) {
System.out.println("Not Healthy!");
} else{
System.out.println("Invalid Weight!");
}
break;
...
}
答案 0 :(得分:0)
你的
} else if(weight <= (month/3) +2 && weight >= ((5 * month)/12) +5) {
部分是错误的,因为这两个条件都不是真的(例如,如果month
是6,那么weight <= 4 && weight >= 7.5
对任何weight
都是假的,如果打印条件"Healthy!"
为false,您将始终到达else
语句并打印"Invalid Weight!"
。
您可能希望其中至少有一个为真(即OR条件):
} else if(weight <= (month/3) +2 || weight >= ((5 * month)/12) +5) {
答案 1 :(得分:0)
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("(1) months then weight in kg");
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int selection = input.nextInt();
switch(selection){
case 1:
System.out.println("Enter age in months: ");
double month = input.nextDouble();
if(month >= 0 && month <= 24){
System.out.println("Enter a weight in kg: ");
} else{
System.out.println("Not a baby anymore");
System.exit(0);
}
double weight = input.nextInt();
if((weight >= 2) &&( weight <= 15 )&&( weight >= (month/3) +2 )&& (weight <= ((5 * month)/12) +5)) {
System.out.println("Healthy!");
} else if((weight <= (month/3) +2 )&& (weight >= ((5 * month)/12) +5)) {
System.out.println("Not Healthy!");
} else{
System.out.println("Invalid Weight!");
}
break;
}
}
}
输出:
/******execution in eclipse************/
/*
(1) months then weight in kg
Enter a number: 1
Enter age in months:
0
Enter a weight in kg:
3
Healthy!
*/