只是想知道我是否正在使用嵌套的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");
}
}
我一直想知道人们对我如何做事的看法。
答案 0 :(得分:2)
我会注意到一些事情:
就个人而言,我认为像
public void method()
{
}
比
更具可读性public void method() {
}
特别是当您拥有包含其他结构的方法时。我确定有些人可能也不介意,但我从来没有听说有人说第一个不可读,而很多人抱怨第二个。抱歉第一个没有正确格式化,但是不允许这样做..似乎网站管理员在这个上不同意我。
标注someVariableName
变量而非some_variable_name
的标准。第一个词应该是小写,所有其他都是大写,它们应该是连续的。方法也是如此。
在check_scores(String)
方法中,您拥有user_input = scores;
,但在实现时不需要全局变量或将传递的变量分配到其他地方,因此这会浪费内存。实际上,由于您的类变量都不在此方法范围之外使用,因此您应该在方法中声明所有这些变量。
我知道这是一个简单的例子,但是为了配合面向对象编程的想法,你的Main
类可能应该在一个单独的文件中并通过在你的主中创建一个对象来运行而不是驱动程序类中的方法。
另外,正如你所提到的,在没有必要的情况下嵌套几个语句可能很草率,因为它很快就会变得难以阅读和跟随。