我刚开始通过阅读一本书并完成练习来自学java。书中的一个练习是让我编写一个使用递归打印对称整数序列的方法。例如:
writeSequence(1); //prints 1
writeSequence(2); //prints 1 1
writeSequence(3); //prints 2 1 2
writeSequence(4); //prints 2 1 1 2
writeSequence(5); //prints 3 2 1 2 3
writeSequence(6); //prints 3 2 1 1 2 3
到目前为止,我的解决方案使用了两种方法实现,看起来不是很优雅:
public class Client {
public static void main(String[] args) {
writeSequence(1);
writeSequence(2);
writeSequence(3);
writeSequence(4);
writeSequence(5);
writeSequence(6);
}
public static void writeSequence(int num) {
writeSequence( (int) Math.round(num/2.0), "desc", true);
if (num % 2 == 0) {
writeSequence( (int) Math.round(num/2.0), "asc", true);
} else {
writeSequence( (int) Math.round(num/2.0), "asc", false);
}
}
public static void writeSequence(int num, String direction, Boolean show_one) {
if (num < 1) {
throw new IllegalArgumentException("less than 1");
} else if (num == 1) {
if (show_one) {
System.out.print(1 + " ");
}
} else {
if (direction.equals("desc")) {
System.out.print(num + " ");
writeSequence(num-1, direction, show_one);
} else {
writeSequence(num-1, direction, show_one);
System.out.print(num + " ");
}
}
}
}
我的问题是:如何仅使用必须采用 ONE 参数的 ONE 方法来解决此问题?现在,我正在实现两种方法,但我只想实现一种来解决问题。