我的代码失败了,但我不知道原因

时间:2021-04-10 12:00:46

标签: java return boolean illegalargumentexception

/**
 * Checks whether a given value is in a given range defined by its lowest and highest possible value
 * Both of the borders of the range (lowestPossible, highestPossible) are considered to be inside of the range
 * An IllegalArgumentException is thrown if the highestPossible value is less than the lowestPossible value
 * @param lowestPossible The lowest possible value of the range
 * @param highestPossible The highest possible value of the range
 * @param guess The value that has been guessed
 * @return <code>true</code> if the guess is withing the given range; <code>false</code> otherwise
 */
public static boolean isWithinBorders(int lowestPossible, int highestPossible, int guess) {
   // return false; // TODO: IMPLEMENT ME (AND DELETE THIS COMMENT AFTERWARDS!!!)

当我运行测试时,我得到了零个错误,但我也得到了一个失败。失败的原因可能是什么?我在控制台中或左侧显示的代码旁边没有收到任何错误信息:(

我的代码:

    if (guess > lowestPossible & guess < highestPossible) { //is value guess between highest & lowest number?
        //if (lowestPossible < highestPossible && highestPossible > lowestPossible) {  //
        return true;
            
    }else if(highestPossible < lowestPossible) {
        throw new IllegalArgumentException("lowestPossible can´t be higher then highestPossible");
            
    }else {
        return false;
    }
}

1 个答案:

答案 0 :(得分:1)

  1. 应首先验证参数 highestlowest
  2. 要求 lowesthighest[lowest, highest] 范围内,而现有代码不包括这些值 (lowest, highest)
  3. & 是按位运算符,&& 应用作逻辑 AND 运算符
  4. 最后一个 return 是多余的

因此,正确的代码可能如下所示:

public static boolean isWithinBorders(int lowest, int highest, int guess) {
    if (highest < lowest) {
        throw new IllegalArgumentException("Lowest must be less than highest");
    }
    return lowest <= guess && guess <= highest;
}
相关问题