Write a
method getUpDownStars() to print an ascending and descending sequence of
integers delimited by a '*'.
getUpDownStars(2,
5) return 2*3*4*5*4*3*2
getUpDownStars(1,3)
return 1*2*3*2*1
getUpDownStars(1,1) return 1*1
getUpDownStars(1,1) return 1*1
public class PrintStars1 { public static String getUpDownStars(int k, int n) { if (k < 0 || n < 0 || k > n) throw new IllegalArgumentException("Illegal Argument Exception"); if (k == n) return k + "*" + k; return getStars(k, n); } private static String getStars(int k, int n) { if (k == n) return k + ""; String str = k + "*" + getStars(k + 1, n); str = str + "*" + (k); return str; } }
Following is
the junit test case for above application.
import static org.junit.Assert.assertEquals; import org.junit.Test; public class PrintStars1Test { @Test public void test1() { assertEquals(PrintStars1.getUpDownStars(2, 2), "2*2"); assertEquals(PrintStars1.getUpDownStars(2, 3), "2*3*2"); assertEquals(PrintStars1.getUpDownStars(2, 4), "2*3*4*3*2"); assertEquals(PrintStars1.getUpDownStars(2, 5), "2*3*4*5*4*3*2"); } @Test(expected = IllegalArgumentException.class) public void test2() { PrintStars1.getUpDownStars(2, 1); } }
No comments:
Post a Comment