简体   繁体   English

使用if-else并且满足所有可能的条件时,为什么在方法中需要附加的return语句

[英]Why do i need an additional return statement in a method when using if-else and all possible conditions are met

My question is about return statements in a method. 我的问题是关于方法中的return语句。 In the method calculatePrice below it accepts an integer as a parameter and the if-else block tests for every possible case (below 0, within the ranges, and at the top of the range) and has a return statement for each. 在下面的方法calculatePrice中,它接受一个整数作为参数,并且对每种可能的情况(0以下,范围内和范围顶部)进行if-else块测试,并为每个语句返回一个语句。 The code below compiles with an error because I don't include a return statement at the bottom, but I'm confused why I need that since it will meet one of the conditions before it ever gets to that last return. 下面的代码编译出错,因为我没有在底部包括return语句,但是我很困惑为什么需要它,因为它在到达最后一个返回值之前会满足条件之一。 Thanks! 谢谢!

import java.text.DecimalFormat;
public class ElectricityCostSolution {
    public static void main(String[] args) {
        DecimalFormat price = new DecimalFormat("$##.00");
        int test1 = 984;
        int test2 = 2984;
        int test3 = 5984;
        System.out.println("The price for " + test1 + "kwh of electricity is " + price.format(calculatePrice(test1)));
        System.out.println("The price for " + test2 + "kwh of electricity is " + price.format(calculatePrice(test2)));
        System.out.println("The price for " + test3 + "kwh of electricity is " + price.format(calculatePrice(test3)));
    }
    public static double calculatePrice(int hours) {
        final double LEVEL_ONE_PRICE = .0577;
        final double LEVEL_TWO_PRICE = .0532;
        final double LEVEL_THREE_PRICE = .0511;
        if (hours <= 1000) {
            return hours * LEVEL_ONE_PRICE;
        } else if (hours > 1000 && hours <= 5000) {
            return (1000 * LEVEL_ONE_PRICE) + (hours - 1000) * LEVEL_TWO_PRICE;
        } else if (hours > 5000) {
            return (1000 * LEVEL_ONE_PRICE) + (4000 * LEVEL_TWO_PRICE) + (hours - 5000) * LEVEL_THREE_PRICE;
        }
    }
}

Why do you need that 3rd if? 为什么您需要第三个? It's always true. 永远是真的。

The compiler will not actually evaluate all your conditions to see if both decisions can really happen. 编译器实际上不会评估您的所有条件,以查看这两个决定是否真的可以发生。 In general, it's not possible to make these sorts of determinations automatically. 通常,不可能自动做出这些确定。

If you make the last condition an else instead of an "else if", then you don't need another return. 如果将最后一个条件设为else而不是“ else if”,则不需要其他返回。

That is because you have added if and else if statements, there is no return statement for the scenario when any of these conditions aren't met. 这是因为您添加了ifelse if语句,当不满足任何这些条件时,该方案没有return语句。

Perhaps you should add an else block of code or simply add one return statement at the end of the code or you can just change your existing code to following 也许您应该添加一个else代码块或仅在代码末尾添加一个return语句,或者您可以将现有代码更改为

    if(hours <= 1000)
    {
      return hours * LEVEL_ONE_PRICE;
    }
    else if(hours>1000 && hours <= 5000)
    {
      return (1000 * LEVEL_ONE_PRICE) + (hours-1000) * LEVEL_TWO_PRICE;
    }
    else 
    {  
     return (1000 * LEVEL_ONE_PRICE) + (4000 * LEVEL_TWO_PRICE) + (hours - 5000) * LEVEL_THREE_PRICE;
    }

Maybe it's because Java doesn't know that all conditions are met. 也许是因为Java不知道是否满足所有条件。 When you compile, it looks for code errors, but I don't think it makes sure your if-else statements are all met. 编译时,它会查找代码错误,但我认为它不能确保满足您的if-else语句。 Just in case, it makes you add a return false; 以防万一,它会使您添加return false; or return true; return true; at the end to make sure that there are no problems. 最后确保没有问题。 I think it is just that the developers don't want to add a check to Java. 我认为只是开发人员不想在Java中添加检查。 Another example of this is setting a variable equal to something else. 另一个例子是将变量设置为其他变量。 Shouldn't it know the difference between var1 = var2 and if (var1 = var2) ? 它不应该知道var1 = var2if (var1 = var2)之间的区别吗?

Correct me if I'm wrong. 如果我错了纠正我。

-Ben -ben

It is because the compiler is not checking your actual conditions, so it warns that if none of your conditions are satisfied then you won't have a return value. 这是因为编译器没有检查您的实际条件,所以它警告说,如果您的条件都不满足,那么您将没有返回值。 That's why very often programming teachers say that a good practice is to store your "return" value in a variable and then actually return it at the end of the procedure. 这就是为什么编程老师经常说一种好的做法是将“返回”值存储在变量中,然后在过程结束时实际返回它。 Because of that and because it is easier to debug. 因此,并且它更易于调试。 For your personal issue, you can just omit the if (hours > 5000) statement and leave it to the last else . 对于您的个人问题,您可以省略if (hours > 5000)语句,然后将其保留到最后else You will obtain the same algorithm (since > 5000 is the case which will satisfy if none of the other does) and the compiler will recognize all the execution paths so it won't throw a warning. 您将获得相同的算法(因为如果没有其他方法,则将满足> 5000),并且编译器将识别所有执行路径,因此不会发出警告。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在所有if-else分支都具有return语句的情况下,方法中的if-else if-else(在循环内)给出“ return语句丢失”的信息? - Why if-else if-else (within a loop) in method gives “return statement missing” while all if-else branches have a return statement? if-else 和 if only when 方法有 return 语句 - 它们相同吗? - if-else and if only when method has return statement - are they same? 当 if 语句中必须满足所有 3 个条件时如何返回某些内容 - How to return something when ALL 3 conditions MUST be met in an if statement 如果不满足if语句中的条件,为什么while循环中的else语句不执行? - Why won't the else statement in my while loop execute when the conditions in the if statement aren't met? 递归方法:为什么我需要return语句? - Recursive method: why do I need return statement? 使用可选项,是否可以在不添加单独的 if-else 语句的情况下提前返回“ifPresent”? - Using optionals, is it possible to return early on "ifPresent" withoud adding a separate if-else statement? 如何将 if-else 语句转换为 switch 语句 - How do i convert an if-else statement to a switch statement 如何将此 if-else 语句转换为 java 中的 switch 语句? - How do I convert this if-else statement into a switch statement in java? 我的 java 方法返回语句有问题,我在 if-else 语句中为未初始化的变量赋值 - I have a problem with a java method return statement, I have given value for an un-initialized variable in an if-else statement 是否可以将使用字符串作为切换值的if-else替换为switch语句? - Is it possible to replace if-else with switch statement using strings as switching values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM