如何将整数放在Java中的范围内?

时间:2017-09-22 13:36:57

标签: java range average

虽然我确信这个答案很简单,但我不确定是否要求我做这项任务。这是我编写的完整代码(所以只是返回!)以及给出的指令:

package code;

/**
 * This class contains a variety of methods that will be used throughout the Ratings and Reviews
 * project.
 */

public class Utilities{

/**
 * Computes the average of two ratings
 *
 * @param rating0 An integer rating in the range of 1-5 inclusive
 * @param rating1 An integer rating in the range of 1-5 inclusive
 * @return the average of rating0 and rating1 as a double
 */
public double averageRating(int rating0, int rating1){

    return ((rating0 + rating1) / 2); // Don't forget to replace this return statement with your own
}

抱歉粘贴后结构不好。我认为我的回报适合于正在做的事情,只要评级可以是任何事情。我知道它只能在1-5之间,那么如何指定呢?

1 个答案:

答案 0 :(得分:1)

如果范围被违反,如何投掷InvalidArgumentException

e.g。

public double averageRating(int rating0, int rating1){
    if (rating0 < 1 || rating0 > 5 || rating1 < 1 || rating1 > 5) {
        throw new InvalidArgumentException("Rating out of range");
    }

    return ((rating0 + rating1) / 2.0); // Don't forget to replace this return statement with your own
}