我有以下代码:
public static void main(final String[] args) {
if (args.length == 0) {
System.out.println("Please provide a correct directory path as an argument!");
} else {
System.out.println("Thanks for using our CodeMetrics\n"
+ "The process Might take a long time, please wait!\n"
+ "Please check the CSV file for the final results!");
File ad = new File(args[0]);
File[] list = ad.listFiles();
for (File f : list) {
CodeMetrics codeMetrics = new CodeMetrics();
codeMetrics.parseCommandLine(f.toString());
codeMetrics.countComplexity(codeMetrics.sourceCodeFile);
// Count LOC (Lines of Code)
codeMetrics.countLines(codeMetrics.sourceCodeFile);
codeMetrics.countTestLines(codeMetrics.testFiles);
codeMetrics.printReport();
codeMetrics.writeReport();
}
}
}
现在我想让用户有机会选择枯萎来调用printReport()
方法或一起召唤printReport()
和writeReport()
。问题是,如果我放置一个if语句,它将位于for循环中,并且用户必须为循环中的每次迭代选择。
我能看到的唯一想法是实现不同的方法如下:
public static void onlyPrint(final String args){
}
public static void printAndWrit (final String args){
}
并且两个方法将具有相同的代码,除了其中一个将具有printReport()而另一个将具有这两个方法。但我对这个解决方案并不满意,因为我相信它会有很多代码减少!有更好的解决方案吗?
谢谢
答案 0 :(得分:3)
Drew Kennedy所说的最有可能是最容易实现的答案。
public static void main(final String[] args) {
if (args.length == 0) {
System.out.println("Please provide a correct directory path as an argument!");
} else {
System.out.println("Thanks for using our CodeMetrics\n"
+ "The process Might take a long time, please wait!\n"
+ "Please check the CSV file for the final results!");
File ad = new File(args[0]);
File[] list = ad.listFiles();
//ask the user here
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number : Would you like to (1) print, or (2) print & write?");
int answer = scan.nextInt();
boolean write = false;
if (answer == 2) {
write = true;
}
for (File f : list) {
CodeMetrics codeMetrics = new CodeMetrics();
codeMetrics.parseCommandLine(f.toString());
codeMetrics.countComplexity(codeMetrics.sourceCodeFile);
// Count LOC (Lines of Code)
codeMetrics.countLines(codeMetrics.sourceCodeFile);
codeMetrics.countTestLines(codeMetrics.testFiles);
//check whether the user wants to write or not
if (write == false) {
codeMetrics.printReport();
} else {
codeMetrics.printReport();
codeMetrics.writeReport();
}
}
}
}
这应该只询问用户一次,并做你需要完成的事情。
答案 1 :(得分:2)
我同意Childishforlife的观点,布尔的解决方案是最简单的方法。我只想提一点优化。
你可以转
//check whether the user wants to write or not
if (write == false) {
codeMetrics.printReport();
} else {
codeMetrics.printReport();
codeMetrics.writeReport();
}
成:
codeMetrics.printReport();
if (write) {
codeMetrics.writeReport();
}
如果我理解了一切正确,可以在两种情况下打印报告。只有写作取决于用户的选择。