40.7k views
0 votes
Write a method called makeStars. The method receives an int parameter that is guaranteed not to be negative. The method returns a String whose length equals the parameter and contains no characters other than asterisks. Thus, makeStars(8) will return ******** (8 asterisks). The method must not use a loop of any kind (for, while, do-while) nor use any String methods other than concatenation. Instead, it gets the job done by examining its parameter, and if zero returns an empty string otherwise returns the concatenation of an asterisk with the string returned by an appropriately formulated recursive call to itself.

User Non
by
5.7k points

1 Answer

4 votes

Answer:

// import the Scanner class

// to allow the program receive user input

import java.util.Scanner;

// The class Solution is defined

public class Solution{

// main method to begin program execution

public static void main(String[] args) {

// scanner object scan is declared

Scanner scan = new Scanner(System.in);

// Prompt the user to enter a number

System.out.println("Enter the number of stars you want: ");

// user input is assigned to numOfStar

int numOfStar = scan.nextInt();

// call the makeStars method

makeStars(numOfStar);

}

// makeStars method print stars using recursion

// the method call itself till starNum == 0

public static void makeStars(int starNum){

if (starNum != 0){

System.out.print("*");

makeStars(starNum -1);

}

}

}

Step-by-step explanation:

The code is well comment and solve the problem using recursion.

User Ffff
by
6.1k points