ruhsx Java递归打印星号?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (128)

我需要编写一个方法来打印下面指定的星形图案。方法的签名只传递1个参数,不能更改。

该方法也不能有循环,必须简单地调用自身并递归地解决问题。您只能使用一种方法来解决此问题,而不是多种方法。

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;
}

调用printAsterisk(4)时,所需的输出应如下所示:

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

但是,当像这个printAsterisk(4)一样调用时,我的方法将打印以下内容:

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

-----解决方案-----所以我找到了问题的解决方案。我稍微改变了方法,并添加了一个全局字符串变量。这允许我操纵字符串然后重置它。以下代码将产生正确的结果......

// Import;
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 
                printAsterisks(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 
        printAsterisks(n-1);
        System.out.println(s.substring(n));
    }
}

printAsterisk(4)时的输出:

*
**
***
****
****
***
**
*
提问于
用户回答回答于

以下是我对解决方案的修改:

    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);
    }

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励