Triangle Recursion Java [closed]

2019-09-27 13:40发布

问题:

takes two numbers m and n on the command line and writes out a triangle pattern of asterisks

public class Triangle {

public static void main(String[] args) {
    int a=0;
    int b=0;
    if(args.length!=0){
        a=Integer.parseInt(args[0]);
        b=Integer.parseInt(args[1]);
    }
    printFirstHalf(a,b);
    printSecondHalf(a,b);
}

public static void printFirstHalf(int m, int n){

    if(m==0){
        return;
    }

    //recursive step
    for(int i=m; i<=n; i++){
        System.out.print("*");
    }
    System.out.println();
    printFirstHalf(m-1,n);


}

public static void printSecondHalf(int m, int n){
    if(m==0){
        return;
    }
    printSecondHalf(m-1,n);

    //recursive step
    for(int i=m; i<=n; i++){
        System.out.print("*");
    }
    System.out.println();


}
}

If 3 and 7 are sent in it should print:

***
****
*****
******
*******
*******
******
*****
****
***

Right now it prints out:

*****
******
*******
*******
******
*****

I know I am close but for some reason I am majorly stuck.

回答1:

Consider this:

public static void printFirstHalf(int m, int n){
    if(m>n){
        return;
    }

    // print asterix
    for(int i=1; i<=m; i++){
        System.out.print("*");
    }
    System.out.println();

    // recurse
    printFirstHalf(m+1,n);
}

Do you see where you went wrong with your other method now?

If you're working with recursion for the first time, I understand that it can be difficult but there is no 'magic' with recursion. Work through the code step-by-step and understand what it does. In this case you weren't actually printing the number of asterix needed. Keep at it.



回答2:

Your first half could be like this (incremental logic> :

public static void printFirstHalf(int m, int n){

    if(m>n){
        return;
    }

    //recursive step
    for(int i=1; i<=m; i++){
        System.out.print("*");
    }
    System.out.println();
    printFirstHalf(m+1,n);

}

Would suggest you to write similar decremental logic for second half