我是这里的新成员,我也是JAVA的初学者。对我来说似乎最抽象的事情就是递归,所以如果我们写3例如下,我在完成一个应该有这个输出的程序时遇到一些困难:
1
12个
123个
12个
1
或者如果我们写5例如它应该打印出来:
1
12个
123个
1234
12345个
1234
123个
12个
1
我可以使用for循环执行此程序,但我必须使用递归,这是我到目前为止所做的:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
如果有人能帮助我,我会很高兴:)。
答案 0 :(得分:2)
您需要实现两个递归函数:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
然后,你需要按顺序调用它们:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
或者采用更对称的方式&#34;:
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
答案 1 :(得分:0)
你可以这样做:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
答案 2 :(得分:0)
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}