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

打印星号的Java递归
EN

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

我需要编写一个方法来打印下面指定的星形图案。该方法的签名仅传入1个参数,无法更改。

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

代码语言:javascript
复制
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)时,所需的输出应如下所示:

代码语言:javascript
复制
*
**
***
****
****
***
**
*

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

代码语言:javascript
复制
*
**
***
****
****
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-16 11:52:15

所以我找到了这个问题的唯一解决方案,它满足了所有问题的要求。我稍微修改了一下程序,并添加了一个全局字符串变量。这使我可以操作字符串,然后对其进行重置。通过编辑方法签名并传递更多参数、使用循环和/或使用多个方法,问题很容易解决。这是解决这个问题的唯一可能的方法,只有一个方法,传入一个参数(一个整数),并且没有循环。下面的代码将产生正确的结果,干杯...

代码语言:javascript
复制
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));
    }
}
票数 0
EN

Stack Overflow用户

发布于 2018-10-15 07:55:02

你的想法效果很好,可以稍微整理一下。在递归之外定义String s有点令人讨厌,而且递归实现本身隐藏了解决方案的对称性。以下是我对您的解决方案的变体:

代码语言:javascript
复制
    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);
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52789416

复制
相关文章

相似问题

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