简体   繁体   English

Java递归打印星号

[英]Java recursion to print asterisks

I need to write a method that will print a star pattern that is specified below.我需要编写一个方法来打印下面指定的星形图案。 The method's signature only passes in 1 parameter, and cannot be changed.该方法的签名仅传入 1 个参数,不能更改。

The method cannot have loops either, must simply call itself and solve the problem recursively.该方法也不能有循环,必须简单地调用自身并递归解决问题。 You can only use ONE method to solve this problem, not multiple.您只能使用一种方法来解决此问题,而不能使用多种方法。

public static void main(String[] args) {
    // Variables
    Scanner in = new Scanner(System.in); 
    Boolean go = true;
    int num;
    String answer;

    // Error catching structure 
    do {
        try {
            // Take input
            System.out.print("Enter a number > 1: ");
            num = in.nextInt();

            // Check to make sure num>1
            if (num <= 1) throw new Exception();

            // Call the method 
            System.out.println(printAsterisk(num));

            // Ask if the user wants to repeat
            System.out.print("Enter 'y' to repeat or 'n' to stop: ");
            answer = in.next().toLowerCase();

            // Check to see if we repeat
            if (answer.equals("n")) go = false; 
            else if (answer.equals("y")) go = true;
            else {
                System.out.println("Invalid input, program terminated.");
                break; // stops the program
            }
        }
        catch (InputMismatchException e) {
            System.out.println("Invalid input try again!");
            in.next(); // discards old token 
        }
        catch (Exception e) {
            System.out.println("Number is less than or equal to 1! Try again!");
        }

    }while(go); 
}

public static String printAsterisk(int n) {
    // Base case
    if (n == 0) return "";

    // Recursive Call
    String str = '*' + printAsterisk(n-1);
    System.out.println(str);

    return str;
}

The output required should look like this when calling printAsterisk(4):调用 printAsterisk(4) 时所需的输出应如下所示:

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

However my method will print the following when called like this printAsterisk(4):但是,当像这样调用 printAsterisk(4) 时,我的方法将打印以下内容:

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

Your idea works well and can be tidied a bit.你的想法很有效,可以稍微整理一下。 Having String s defined outside of the recursion is a bit yucky and the recursion implementation itself hides the symmetry of the solution a bit.在递归之外定义String s有点令人讨厌,并且递归实现本身稍微隐藏了解决方案的对称性。 Here is my variation on your solution:这是我对您的解决方案的变体:

    static void printAsterisk(int n) {
        printAsterisk(n, 1);
    }

    static void printAsterisk(int n, int m) {
        if (n < m) return;

        printStars(m);
        printAsterisk(n, m + 1);
        printStars(m);
    }

    static void printStars(int count) {
        char[] stars = new char[count];
        Arrays.fill(stars, '*');
        System.out.println(stars);
    }

    public static void main(String[] args) {
        printAsterisk(4);
    }

So I found the only solution to the problem that meets all of the question requirements.所以我找到了满足所有问题要求的问题的唯一解决方案。 I changed the program a little bit and I added a global string variable.我稍微更改了程序并添加了一个全局字符串变量。 This allows me to manipulate the string and then reset it.这允许我操作字符串然后重置它。 Question was easy to solve by either editing the method signature and passing in more parameters, using loops, and or using multiple methods.通过编辑方法签名并传入更多参数、使用循环和/或使用多种方法,问题很容易解决。 This is the ONLY possible way to solve this problem with one method, one parameter being passed in (an integer), and NO loops.这是使用一种方法、传入一个参数(整数)并且没有循环来解决此问题的唯一可能方法。 The following code will produce the right result, cheers...以下代码将产生正确的结果,欢呼...

import java.util.*;

public class RecursiveAsterisks {
    // Global Variables
    private static Scanner in = new Scanner(System.in); 
    private static Boolean go = true;
    private static int num;
    private static String answer;
    private static String s = "*";

    public static void main(String[] args) {    
        // Error catching structure 
        do {
            try {
                // Take input
                System.out.print("Enter a number > 1: ");
                num = in.nextInt();

                // Check to make sure num>1
                if (num <= 1) throw new Exception();

                // Call the method 
                printAsterisk(num);
                s = "*"; // reset string

                // Ask if the user wants to repeat
                System.out.print("Enter 'y' to repeat or 'n' to stop: ");
                answer = in.next().toLowerCase();

                // Check to see if we repeat
                if (answer.equals("n")) go = false; 
                else if (answer.equals("y")) go = true;
                else {
                    System.out.println("Invalid input, program terminated.");
                    break; // stops the program
                }
            }
            catch (InputMismatchException e) {
                System.out.println("Invalid input try again!");
                in.next(); // discards old token 
            }
            catch (Exception e) {
                System.out.println("Number is less than or equal to 1! Try 
again!");
            }
        }while(go);
    }

    // Recursive Method
    public static void printAsterisk(int n) {
        // Base case
        if (n == 0) return;

        // Recursive Call
        System.out.println(s);
        s += '*'; // concatenate string 
        printAsterisk(n-1);
        System.out.println(s.substring(n));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM