如何编写两个return语句?

时间:2018-12-03 14:37:03

标签: java

我应该写一个方法,该方法采用两个代表间隔的整数。该方法应返回整数之和。如果第一个整数为负,或者第二个整数小于第一个整数,则该方法应返回-1。我不明白我应该怎么做return -1语句。我应该做一个if语句吗?

public static int sumRange(int i1, int i2){
    int sum = 0;
    for(int i = i1; i <= i2; i++){
        sum = i + sum;
    }
    return sum;
}

2 个答案:

答案 0 :(得分:4)

只需添加if条件:

    if (i1<0 || i2<i1){
      return -1;
    }

完整代码:

public static int sumRange(int i1, int i2){
    if (i1<0 || i2<i1){
      return -1;
    }

    int sum = 0;
    for(int i = i1; i <= i2; i++){
        sum = i + sum;

    }
    return sum;


}

答案 1 :(得分:0)

当条件满足时,您只需返回-1。

public static int results(int a, int b) {

        //If the first number is negative or the second number is higher than first, returns -1
        if (a < 0 || b < a) {
            return -1;
        }

        int sum = 0; //In this variable you will store your sum
        //iterate from A until B and sum
        for (int i = a; i <= b; i++) {
            sum += i;
        }

        return sum;
    }