我使这段代码非常糟糕。谁能告诉我如何使此代码更好,更小,更有效。我知道有一种更好的方法可以做到这一点,但无法弄清楚该怎么做。
public static String finalResult(String result[])
{
String final_result = "";
if (result[0].contains("NO ANSWERS"))
final_result += "-";
else if (Integer.parseInt(result[0]) < 50 & Integer.parseInt(result[0]) >= 0)
final_result += "E";
else if (Integer.parseInt(result[0]) > 50)
final_result += "I";
else
final_result += "X";
if (result[1].contains("NO ANSWERS"))
final_result += "-";
else if (Integer.parseInt(result[1]) < 50 && Integer.parseInt(result[1]) >= 0)
final_result += "S";
else if (Integer.parseInt(result[1]) > 50)
final_result += "N";
else
final_result += "X";
if (result[2].contains("NO ANSWERS"))
final_result += "-";
else if (Integer.parseInt(result[2]) < 50 && Integer.parseInt(result[2]) >= 0)
final_result += "T";
else if (Integer.parseInt(result[2]) > 50)
final_result += "F";
else
final_result += "X";
if (result[3].contains("NO ANSWERS"))
final_result += "-";
else if (Integer.parseInt(result[3]) < 50 && Integer.parseInt(result[3]) >= 0)
final_result += "J";
else if (Integer.parseInt(result[3]) > 50)
final_result += "P";
else
final_result += "X";
return final_result;
}
我需要它花费尽可能少的时间。我是一名7年级生,试图完成我的CS作业。它必须是最好的。请帮助我。
答案 0 :(得分:0)
public static String finalResult(String result[]) {
StringBuilder final_result = new StringBuilder();
String[] betweenZeroAnd50 = new String[] { "E", "S", "T", "J" };
String[] greatherThan50 = new String[] { "I", "N", "F", "P" };
if (result.length == 4) {
//instead of writing 3 times if with same condition and only index changes so avoid repeatly code and use loop.
for (int i = 0; i < 4; i++) {
if (result[i].contains("NO ANSWERS")) {
final_result.append("-");
} else if (isNumeric(result[i]) && Integer.parseInt(result[i]) >= 0
&& Integer.parseInt(result[0]) < 50) {
final_result.append(betweenZeroAnd50[i]);
} else if (isNumeric(result[i]) && Integer.parseInt(result[i]) > 50) {
final_result.append(greatherThan50[i]);
} else {
final_result.append("X");
}
}
}
return final_result.toString();
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}