Java递归以打印星号

时间:2018-10-13 04:01:44

标签: java algorithm recursion

我需要编写一个方法,该方法将打印下面指定的星型。该方法的签名仅传入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)这样调用时,它将打印以下内容:

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

2 个答案:

答案 0 :(得分:1)

您的想法很好,可以整理一下。在递归之外定义String s有点麻烦,并且递归实现本身隐藏了解决方案的对称性。这是我为您提供的解决方案:

    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 :(得分:0)

因此,我找到了满足所有问题要求的唯一解决方案。我稍稍更改了程序,并添加了一个全局字符串变量。这使我可以操纵字符串,然后将其重置。通过编辑方法签名并使用循环或多个方法来输入方法参数并传递更多参数,很容易解决问题。这是用一种方法来解决此问题的唯一可能的方法,一个参数传入(整数),并且没有循环。以下代码将产生正确的结果,欢呼...

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