How do I write the following method using recursion in JAVA: public static void
ID: 3820790 • Letter: H
Question
How do I write the following method using recursion in JAVA:
public static void printStars(int rows)
{
for (int x = 1; x <= rows; x++)
{
System.out.print("*");
}
}
public boolean isIn(String pattern, String target)
{
return true;
}
//main:
public static void main(String[] args)
{
recTest utils = new recTest();
utils.printStars(0);
utils.printStars(5);
String[] patterns = { "al ", "Sta", "eat", "ney" };
for(int ii = 0; ii < patterns.length; ++ii)
{
System.out.println("Is this pattern '" + patterns[ii] + "' in 'Barney Station? " + utils.isIn(patterns[ii], "Barney Sation"));
}
}
Explanation / Answer
package myProject;
public class RecTest
{
//Recursive call method to print *
public static void printStars(int rows)
{
//Checks if rows value is zero then stop
if(rows == 0)
return;
//Otherwise print the star and recursively call the method till rows value is zero
else
{
//Prints *
System.out.print("*");
//Calls the method by decrementing the value of rows by 1
printStars(--rows);
}//End of else
}//End of method
//Method to return true
public boolean isIn(String pattern, String target)
{
return true;
}//End of method
//Main method
public static void main(String[] args)
{
RecTest utils = new RecTest();
utils.printStars(0);
utils.printStars(5);
String[] patterns = { "al ", "Sta", "eat", "ney" };
//Loops till the length or patterns
for(int ii = 0; ii < patterns.length; ++ii)
{
System.out.println("Is this pattern '" + patterns[ii] + "' in 'Barney Station? " + utils.isIn(patterns[ii], "Barney Sation"));
}//End of loop
}//End of main
}//End of class
Output:
*****Is this pattern 'al ' in 'Barney Station? true
Is this pattern 'Sta' in 'Barney Station? true
Is this pattern 'eat' in 'Barney Station? true
Is this pattern 'ney' in 'Barney Station? true
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.