递归制作钻石

时间:2019-04-06 21:30:38

标签: java recursion

//Making a diamond using recursive methods. The diamond is filled with //whitespace then outlined using / and \.


    //Using java, and has to be using recursive methods.

public static void diaTop(int w){ //this is to make top of diamond
        if(w == 0 )return;
        else System.out.print('/'); //printing left side of diamond
        for(int i = 0; i < w; i++){ //for loop to make spaces
            System.out.print(" ");
        }
            System.out.print('\\'); //printing right side of diamond
            System.out.println();
             diaBot(w-1);
        }

//很难绕过顶部,所以从小处开始然后扩大。

    public static void diaBot(int w){ //this is to make bottom of diamond
        if(w == 0 )return;
        else System.out.print('\\');//printing left side of diamond
        for(int i = 0; i < w; i++){ //for loop to make spaces
            System.out.print(" ");
        }
            System.out.print('/'); //printing right side of diamond
            System.out.println();
             diaBot(w-1);
        }


    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.println("Input width of diamond: ");
        int w = scnr.nextInt(); //getting width of diamond.
        diaTop(w);
        diaBot(w);
    }

/ *输出
    / \     \ /     \ /     \ /     \ /     \ /     \ /     \ /     \ /     \ / * /

1 个答案:

答案 0 :(得分:0)

我想出了一个自上而下的解决方案,虽然不是最花哨的,但是它进行了递归调用,任何教授都希望看到它。最好在星期六晚上上班。    钻石看起来确实有点躲闪,但是您可以随时按照自己喜欢的方式修剪钻石。

class Diamond {

void draw(int width, int height) {
    if (height - width == height) {
        return;

    } else {
        width -= 2;
        //this bit right here works out the width of spaces
        System.out.print("\n\\");
        for (int i = 0; i < width; i++)
            System.out.print(" ");
        System.out.print("/");

        //This calls the whole thing again, right recursion.
        draw(width, height);
    }
}

void drawTop(int width, int height) {
    if (height - width == height) {
        return;
    } else {

        width -= 2;
       //This does the same as above but in reverse...
        System.out.print("\n/");
        for (int i = 0; i <(height - 2) - width ; i++)
            System.out.print(" ");
        System.out.print("\\");

        //The bit is called here, resursion...
        drawTop(width, height);

    }
}
}

public class Main {

public static void main(String[] args) {

    Diamond diamond = new Diamond();

    //Its not too fancy here, but its right recursion.
    //Go ahead, an add your scanner ere if ya like...
    diamond.drawTop(8,8);
    diamond.draw(8, 8);

}
}