这是我的任务,我尝试仅使用简短的if语句来执行此操作,我唯一遇到的错误是语法为“(0.5 java - 简短的if陈述“内部”简短的if陈述-LMLPHP

    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;
}


在可读性/可维护性方面,您还应该考虑以一种易于编写到表中的方式编写此代码:

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 - 简短的if陈述“内部”简短的if陈述,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34383801/

10-09 05:12