gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:34:13 25 4
gpt4 key购买 nike

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;
}
}

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

最佳答案

目前的问题是,如果 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
}

此外,这并没有达到您的预期:

int minutes = time.charAt(0);

...例如,'1' 的值为 49。当您使用 Double.parseDouble 表示分钟:秒的分钟部分时,您真的想要一个double,还是真的想要一个double想要一个int?您真的希望像 .5:20 这样的内容表示 50 秒吗?

最后,请考虑一下“.:....”和“..:....”之间的唯一区别在于您处理 session 记录的方式,真的。在这两种情况下,您都可以只解析一个整数:

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);
}

现在假设您希望 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 */
}

关于java - 当方法包含多个具有多个返回值的 if 语句时,如何从方法中获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19675276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com