Sunday, 23 August 2015

print stars using recursion

Write a program that takes an integer ‘n’ as input and print n ‘*’ s.

printStars(2) = “**”
printStars(3) = “***”
public class PrintStars {

 public static String getStars(int n) {
  if (n <= 0)
   throw new IllegalArgumentException("Input should > 0");

  return getStarsData(n);
 }

 private static String getStarsData(int n) {
  if (n == 0)
   return "";
  return "*" + getStarsData(--n);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PrintStarsTest {

 @Test
 public void test1(){
  assertEquals("*", PrintStars.getStars(1));
  assertEquals("**", PrintStars.getStars(2));
  assertEquals("***", PrintStars.getStars(3));
  assertEquals("****", PrintStars.getStars(4));
 }
 
 @Test(expected=IllegalArgumentException.class)
 public void test2(){
  PrintStars.getStars(-1);
 }
}



No comments:

Post a Comment