当方法包含多个具有多个返回的if语句时,如何从方法获取返回值?

use*_*063 2 java if-statement return return-value

public static double changeToSpeed(String time, int distance)
{
  if(time.indexOf(":") == 1){
    int minutes = time.charAt(0);
    String sec = time.substring(3, 7);
    double seconds = Double.parseDouble(sec);

    double totalTime = 60 * minutes + seconds;
    double endSpeed = distance / totalTime;
    return endSpeed;
  }
  else if(time.indexOf(":") == 2){
    String min = time.substring(0, 2);
    String sec = time.substring(3, 7);

    double minutes = Double.parseDouble(min);
    double seconds = Double.parseDouble(sec);

    double totalTime = 60 * minutes + seconds;
    double endSpeed = distance / totalTime;
    return endSpeed;
  }
  else if(time.indexOf(":") == -1){
    int minutes = 0;
    double seconds = Double.parseDouble(time);

    double totalTime = 60 * minutes + seconds;
    double endSpeed = distance / totalTime;
    return endSpeed;
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试根据字符串时间中":"的位置获得不同的返回值.这给了我一个问题,在方法的主要部分没有返回值,但是当我这样做时,它给了我一个不同的错误,说我有太多的返回语句.我需要帮助.

Jon*_*eet 5

目前的问题是,如果time.indexOf(":")不返回1,2或-1 ,则您的方法不会返回任何内容.在那种情况下你想做什么?例如,您可能想要抛出异常.你应该弄清楚在那种情况下你想要发生什么 - 然后你就可以弄清楚如何实现它.

我还建议一个重构开始:这个方法的大部分是解析时间; 然后你用距离和解析的时间做同样的事情.因此,将时间解析提取到单独的方法:

public static double changeToSpeed(String time, int distance) {
    double totalTime = parseTime(time);
    return distance / totalTime;
}

private static double parseTime(String time) {
    // Now you *only* have to deal with time in here
}
Run Code Online (Sandbox Code Playgroud)

此外,这不符合您的预期:

int minutes = time.charAt(0);
Run Code Online (Sandbox Code Playgroud)

......例如,将为'1'提供49.当你使用Double.parseDouble分钟的几分钟时:秒,你真的想要一个double,或者你真的想要一个int?你真的期待.5:2050秒的意思吗?

最后,考虑一下你的".:......"和"......:......"之间的唯一区别就在于你如何处理分钟.在这两种情况下,您只需解析一个整数:

int colon = time.indexOf(':');
// If we don't have a colon, just assuming it's minutes:seconds in some form
if (colon != -1) {
    int minutes = Integer.parseInt(time.substring(0, colon));
    double seconds = Double.parseDouble(time.substring(colon + 1));
    return minutes * 60 + seconds;
} else {
    return Double.parseDouble(time);
}
Run Code Online (Sandbox Code Playgroud)

现在假设您希望100:30.5成为有效时间.如果你真的只想要在1或2位置冒号,你应该检查:

if (colon == 1 || colon == 2) {
    int minutes = Integer.parseInt(time.substring(0, colon));
    double seconds = Double.parseDouble(time.substring(colon + 1));
    return minutes * 60 + seconds;
} else if (colon == -1) {
    return Double.parseDouble(time);
} else {
    throw new /* some appropriate exception type */
}
Run Code Online (Sandbox Code Playgroud)