只是想知道如果我使用嵌套的if語句太多。我一直在環顧四周,似乎人們試圖不使用它們。代碼也看起來雜亂無章?無論如何它是這樣的:我的代碼是草率/糟糕嗎?
import java.util.Arrays;
public class Main {
private String user_input = "";
private int max_score = 6;
private int sum;
private void check_scores(String scores){
user_input = scores;
String[] temp;
// Check if user_input is valid
//^Match with beginning of line | [0-9] Allow 0-9 | , Allow comma | + Match one or more | $ Match End of line
if (user_input.matches("^[0-9,]+$")) {
// Check if string starts with an ,
if(user_input.charAt(0) == ',') {
// If it does parse and substring to remove them
// otherwise the following regex leaves one behind
int i = 0;
while (!Character.isDigit(user_input.charAt(i))) i++;
int j = user_input.length();
user_input = user_input.substring(i,j);
}
// (.) Match any character) | \1 If it is followed by itself | + Match one or more | $1 replace by the first captured char.
user_input = user_input.replaceAll("(.)\\1+", "$1");
System.out.println(user_input);
// Split at the ',' and put each number in it's own cell in the array
temp = user_input.split(",");
System.out.println(Arrays.toString(temp));
// Check if temp is equal to max_scores
if (temp.length == max_score){
int[] ui_array = new int[temp.length];
// Parse String[] into int[]
for (int i = 0; i < temp.length; i++){
try {
ui_array[i] = Integer.parseInt(temp[i]);
} catch (NumberFormatException nfe) {}; // If triple checking isn't enough...
}
System.out.println("temp array(String): " + Arrays.toString(temp));
System.out.println("ui_array(int): " + Arrays.toString(ui_array));
// Add up all elements in ui_array
for (int j = 0 ; j < ui_array.length; j++) {
sum += ui_array[j];
}
System.out.println("Scores sum:" + sum + " Number of scores:" + ui_array.length + " Number of ends:" + ui_array.length/6);
}
else {
System.out.println("You have " + temp.length + " scores. Acceptable amount is " + max_score);
}
}
else {
System.out.println("Invalid Input. (Only #'s and ,'s allowed)");
}
}
public static void main(String[] args) {
Main main = new Main();
main.check_scores("1,M,7,10,,4,8,");
main.check_scores("1,6,7,10,,4,8,,,,,,,1,2,6,10,2,10");
main.check_scores(",,,,,,,1,2,6,10,2,10");
main.check_scores("10,2,1,5,7,1");
main.check_scores("6,2, ,,5,6,1");
}
}
我剛纔一直想知道一段時間人們怎麼想我如何去做事情。
這種問題更適合[CodeReview.SE](http://codereview.stackexchange.com/)。 – irrelephant 2014-11-21 05:25:09
考慮重構該方法。 – 2014-11-21 05:26:44
爲什麼重命名'scores'?如果你想叫它'user_input',只需重命名參數即可。此外,你應該在你的條件之後做一個新的線。您還應該將temp重命名爲有意義的內容;我使用temp的唯一時間就是它僅僅用於幾行中的小事,但你使用它很多,所以它應該有一個描述性的名字。我低估了這個問題,因爲就像不像大象說的那樣,這是CodeReview Stack Exchange的用處。 – 2014-11-21 05:43:37