简短的 if 语句 "inside" 简短的 if 语句

Short if-statement "inside" short if-statement

这是我的任务,我试图只用简短的 if 语句来完成,我得到的唯一错误是语法中有“( 0.5<=ratio<2)",除此之外,构造正确吗?

    Scanner scn = new Scanner(System.in);
    int years,kg,cm,MenuA,MenuB,MenuC,A,B,C;
    String not;
    double ratio = cm/kg;
    System.out.println("Please enter your age (years), weight(kg) and height(cm) in that order with spaces");
    years = scn.nextInt();
    kg = scn.nextInt();
    cm = scn.nextInt();

    MenuA = (20<years<<11||40<<years<21)&&(0.5<=ratio<2)?A:MenuB;
    MenuB = (20<years<<11)&&(2<=ratio<<3.5)?B:MenuC;
    MenuC = (40<<years<21)&&(2<=ratio<<3.5)?C:not;

}

}

20 < years < 11

那是无效的 Java 代码。无论您首先评估哪个操作数,结果都将是 boolean 类型,它不会与 int.

进行比较

你需要做很长的路要走:

20 < years && years < 11

或者为此创建一个方法:

betweenExclude(20, years, 11);

boolean betweenExclude(int a, int b, int c) {
   return a < b && b < c;
}

也许还有

boolean betweenIncludeLeft(double left, double number, double right) {
  return left <= number && number < right;
}

就可读性/可维护性而言,您还应该考虑以一种易于翻译成您的方式编写此内容table:

enum Age {
  ELEVEN_TO_TWENTY,
  TWENTYONE_TO_FORTY
};

Age age; 
if(between(11, years, 20)) {
   age = Age.ELEVEN_TO_TWENTY;
}
if(between(21, years, 40)) {
   age = Age.TWENTYONE_TO_FORTY;
}

体重与身高的比例相似

以后

if(age.euqals(Age.TWENTYONE_TO_FORTY) && weightratio.equals(WeightRatio.LOW)) {
   //A 
}

评论

您的年龄检查应该包括您的两个界限。 11和20必须,否则10和11岁的人会退学

谢谢大家,成功了:

导入java.util.Scanner;

publicclass电梯{ public static void main(String[] args){

    Scanner scn = new Scanner(System.in);
    int years;
    double kg,cm;
    System.out.println("Please enter your age (years), weight(kg) and height(cm) in that order with spaces");
    years = scn.nextInt();
    kg = scn.nextDouble();
    cm = scn.nextDouble();
    double ratio = cm/kg;
    int MenuA,MenuB,MenuC;
    int A,B,C;

    MenuC = (21<=years&&years<=40)&&(2<=ratio&&ratio<3.5)?'C':'N';
    MenuB = (11<=years&&years<=20)&&(2<=ratio&&ratio<3.5)?'B':MenuC;
    MenuA = ((11<=years&&years<=20||21<=years&&years<=40)&&(0.5<=ratio&&ratio<2))?'A':MenuB;

    System.out.println("Your menu is: " + (char)MenuA);

}

}