In: Computer Science
Create a new Java project called 1410_Recursion. Add a package recursion and a class Recursion. Include the following three static methods described below. However, don't implement them right away. Instead, start by returning the default value followed by a // TODO comment.
Create a second source folder called test. It should include a class RecursionTest. That's where you will write the JUnit tests for the three methods above.
Once you have written the JUnit tests, implement the methods.
Recursion.java
public class Recursion {
public static int sumOfDigits(int n) {
// we cannot sum -ve elements so calculating absolute
n = Math.abs(n);
// if n is 0 then return 0
// else calculate sum of digits
if(n==0)
return 0;
return n%10+sumOfDigits(n/10);
}
public static int countSmiles(char[] letters, int index) {
// if index is 0 then we cannot count further
if(index==letters.length)
return 0;
// checking index if it is less than length of letters
// and checking for smile characters
if(index+1 < letters.length &&
letters[index]==':'&& letters[index+1]==')') {
// if smile found add 1
return 1 + countSmiles(letters, index+2);
}else {
return countSmiles(letters, index+1);
}
}
public static String toUpper(String str) {
// if length is 1 return the upper case
if(str.length()==1) {
return str.toUpperCase();
}
// converting to upper case character
char upper =Character.toUpperCase(str.charAt(0));
// concatenating recursively
return upper+" "+toUpper(str.substring(1,str.length()));
}
}
RecursionTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class RecursionTest {
@Test
public void DigitsSumTest() {
int sum;
// Test1
// returns the calculated sum
sum = Recursion.sumOfDigits(-34);
// tests whether the sum is equal
assertEquals(7, sum);
// Test 2
sum = Recursion.sumOfDigits(1038);
assertEquals(12, sum);
}
@Test
public void CountSmilesTest() {
int count;
char[] ch;
// Test 1
// character array
ch = new char[] {':',')',' ','L','i','f','e',
' ' ,'i','s',' ' ,'g','o','o','d',' ',':',')'};
// returns the calculated counted smiles
count = Recursion.countSmiles(ch, 0);
assertEquals(2, count);
// Test 2
ch = new char[] {'H','a','p','p','y',' ','D',
'a' ,'y',' ',':' ,')',':',')',':',')','!'};
count = Recursion.countSmiles(ch, 0);
assertEquals(3, count);
// Test 3
ch = new char[] {'a',':','b','(','c',')',':',' ' ,')','e'};
count = Recursion.countSmiles(ch, 0);
assertEquals(0, count);
}
@Test
public void UpperTest() {
String s;
// test 1
s= "Hi there!";
// returns the upper case letter
s = Recursion.toUpper(s);
// tests whether it is same
assertEquals(s,"H I T H E R E !");
}
}
Code
Recursion.java
RecursionTest.java
Output