switch、if-else 和数学

switch, if-else and math

这只是部分代码。因此,出于某种原因,当我尝试 运行 这个并且值在可接受的范围内时,我得到了 "Invalid weight!" 响应,但它不应该像 else 语句那样做。

所以...我 select 1 作为我想要的 selection 我应该输入以月为单位的年龄和以公斤为单位的体重。年龄必须在 0 到 24 个月之间。重量必须在 2 到 15 公斤之间。

If weight(kg) >= (age(months))/3 + 2 and 
   weight(kg) <= (5*age(months))/12 + 5... 

我想打印出来 "Healthy" 如果不在那个范围内 - 不健康。

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;

...
}

你的

} else if(weight <= (month/3) +2 && weight >= ((5 * month)/12) +5) {

部分是错误的,因为两个条件不能同时为真(例如,如果 month 为 6,则得到 weight <= 4 && weight >= 7.5,这对任何 weight 都是假的) ,因此如果打印 "Healthy!" 的条件为假,您将始终到达 else 语句并打印 "Invalid Weight!".

您可能希望其中至少有一个为真(即 OR 条件):

} else if(weight <= (month/3) +2 || weight >= ((5 * month)/12) +5) {
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!
*/