首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >打印星号的Java递归

打印星号的Java递归
EN

Stack Overflow用户
提问于 2018-10-13 12:01:44
回答 2查看 1.1K关注 0票数 -2

我需要编写一个方法来打印下面指定的星形图案。该方法的签名仅传入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)时,我的方法将输出以下内容:

*
**
***
****
****
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52789416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档