【问题标题】:Short if-statement "inside" short if-statement短 if 语句“内部”短 if 语句
【发布时间】:2016-03-26 19:49:53
【问题描述】:

这是我的任务,我正在尝试仅使用简短的 if 语句来执行此操作,我得到的唯一错误是使用 "(0.5",除此之外,施工对吗?

    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
  • 你也不能写0.5&lt;=ratio&lt;2。它只是 Java 不支持的语法。
  • 我认为您误解了您可以使用类似于5 &lt; x &lt; 7 的表达式来表示“x 介于 5 和 7 之间”。这在 Java 中不存在。而&lt;&lt;确实是移位操作,不是比较操作。

标签: java eclipse if-statement operators short


【解决方案1】:

谢谢大家,成功了:

导入 java.util.Scanner;

公共级电梯{ 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);

}

}

【讨论】:

    【解决方案2】:
    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 必须在 in,否则 10 和 11 岁的人会退出。

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 2021-08-20
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2018-08-19
      相关资源
      最近更新 更多