gpt4 book ai didi

java - 如何重写此方法以删除多余的 if 语句?

转载 作者:搜寻专家 更新时间:2023-11-01 04:04:36 25 4
gpt4 key购买 nike

如何重写此方法以最大程度地提高代码效率并最小化代码长度?

注意:HEADER是之前定义的常量。

private static URL getURL(String OS, String type, String size) {
String prefix = "";
String prefixLarge = "";
if (type.equals("image")) {
prefix = HEADER + "/image";
prefixLarge = HEADER + "/image_large";
} else {
prefix = HEADER + "/file";
prefixLarge = HEADER + "/file_raw";
}
String suffix = ".zip";
String url = "";
if (OS.contains("Win7.32bit")) {
// win7-32bit system
url = prefix + "Win7.32bit" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "Win7.32bit" + suffix;
}
} else if (OS.contains("Win7.64bit")) {
// win7-64bit system
url = prefix + "Win7.64bit" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "Win7.64bit" + suffix;
}
} else if (OS.contains("WinXP")) {
// winxp-32bit system
url = prefix + "WinXP" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "WinXP" + suffix;
}
} else if (OS.contains("WinXP.64bit")) {
// winxp-64bit system
url = prefix + "WinXP.64bit" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "WinXP.64bit" + suffix;
}
} else if (OS.contains("10.04")) {
// ubuntu10.04 system
url = prefix + "ubuntu10.04" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "ubuntu10.04" + suffix;
}
} else if (OS.contains("12.04")) {
// ubuntu12.04 system
url = prefix + "ubuntu12.04" + suffix;
if (size.contains("origin")) {
url = prefixLarge + "ubuntu12.04" + suffix;
}
}
return url;
}

最佳答案

创建一个包含所有操作系统名称的 Strings 数组。然后使用 for 循环遍历该数组。

像这样:

String[] osNames = { "Win7.32bit", "Win7.64bit", "10.04" };
String[] osTypes = { "Win7.32bit", "Win7.64bit", "ubuntu10.04" };
for (int i = 0; i < Math.min(osNames.length, osTypes.length); i++) {
if (OS.contains(osName[i])) {
url = prefix + osType[i] + suffix;
if (size.contains("origin")) {
url = prefixLarge + osType[i] + suffix;
}
break;
}
}

关于java - 如何重写此方法以删除多余的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14166545/

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