利用分解与抽象,如果我们想输出100遍*#*$*%,代码应该如何写更好?
A.
System.out.print(“*”); System.out.print(“#”); System.out.print(“*”); System.out.print(“$”); System.out.print(“*”); System.out.print(“%”); ...//省略98遍 System.out.print(“*”); System.out.print(“#”); System.out.print(“*”); System.out.print(“$”); System.out.print(“*”); System.out.print(“%”);
B.
void printOnce (){ System.out.print(“*”); System.out.print(“#”); System.out.print(“*”); System.out.print(“$”); System.out.print(“*”); System.out.print(“%”); } void printHundredTimes(){ for(int i=0;i<100;i++) printOnce (); }
C.
void printSharp(){ System.out.print(“*”); System.out.print(“#”); } void printDollar(){ System.out.print(“*”); System.out.print(“$”); } void printPercentage(){ System.out.print(“*”); System.out.print(“%”); } void printOnce (){ printSharp(); printDollar(); printPercentage(); } void printHundredTimes(){ for(int i=0;i<100;i++) printOnce (); }
D.
void printStar(){ System.out.print(“*”); } void printSharp(){ printStar(); System.out.print(“#”); } void printDollar(){ printStar(); System.out.print(“$”); } void printPercentage(){ printStar(); System.out.print(“%”); } void printOnce (){ printSharp(); printDollar(); printPercentage(); } void printHundredTimes(){ for(int i=0;i<100;i++) printOnce (); }