首页 > 解决方案 > 我的逻辑运算符 if 语句中的无尽错误

问题描述

我对 java 很陌生,因此我不确定如何修复我的代码上的错误,在 java 上尝试了一个逻辑运算符,但被每个语句行上的重复错误所淹没(“非法开始类型”,“非法开始of expression”、“not a statement”和“ ';' expected”)我是否使用了错误的代码形式?

   if (gender = "m") {
        if (age >=18 & <30 && vo2max >= 40 && <=60){
            EligibleSport = "Basketball";
        }
        if (age >= 18 & <26 && vo2max >= 62 & <=74){
            EligibleSport = "Biycling";
        }
        if (age >= 18 & <26 && vo2max >= 55 & <=67){
            EligibleSport = "Canoeing";
        }
        if (age >= 18 & <22 && vo2max >= 52 & <=58){
            EligibleSport = "Gymnastics";
        }
        if (age >= 10 & <25 && vo2max >= 50 & <=70){
            EligibleSport = "Swimming";
        }

标签: java

解决方案


问题

  1. 比较运算符通常是二元运算符。所以他们需要两个参数。
  2. Java 期望返回比较boolean,这是通过&&or实现的||。问题中使用的某些运算符按位计算,仅当操作数为&时才会返回。如果错误地使用最终导致,它将返回意想不到的结果booleanbooleanboolean
  3. 字符串应与“equals”或“equalsIgnoreCase`进行比较

解决方案

        if ("m".equals(gender)) {
            if (age >= 18 && age < 30 && vo2max >= 40 && vo2max <= 60) {
                eligibleSport = "Basketball";
            }
            if (age >= 18 && age < 26 && vo2max >= 62 && vo2max <= 74) {
                eligibleSport = "Biycling";
            }
            if (age >= 18 && age < 26 && vo2max >= 55 && vo2max <= 67) {
                eligibleSport = "Canoeing";
            }
            if (age >= 18 && age < 22 && vo2max >= 52 && vo2max <= 58) {
                eligibleSport = "Gymnastics";
            }
            if (age >= 10 && age < 25 && vo2max >= 50 && vo2max <= 70) {
                eligibleSport = "Swimming";
            }
        }

推荐阅读