Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CSCI 2120 Homework 2: Recursion Introduction For this assignment you will implem

ID: 3888291 • Letter: C

Question

CSCI 2120 Homework 2: Recursion Introduction For this assignment you will implement two recursive methods and write JUnit tests for each one. You may write all three methods in the same class file. For this assignment, you will be required to write Javadoc-style documentation for all of your methods, including the test methods. Procedure 1) Write a recursive method to compare two Strings using alphabetical order as the natural order (case insensitive): 50 points public static int compareTo(String s1, String s2) The function should return an integer with the following convention: s1 comes before s2 s1 == (or indistinguisable from) s2 s1 comes after s2 returns an integer less than 0 returns 0 returns an integer greater than 0

Explanation / Answer

Please find my answer.

public class StringCompare {

  

   public static int compareTo(String s1, String s2) {

      

       // if string is null then replace with empty string

       s1 = s1==null ? "" : s1;

       s2 = s2==null ? "" : s2;

      

       if(s1.isEmpty() && s2.isEmpty())

           return 0;

      

       if(s1.isEmpty())

           return -1;

      

       if(s2.isEmpty())

           return 1;

      

       if(s1.charAt(0) < s2.charAt(0))

           return -1;

      

       if(s1.charAt(0) > s2.charAt(0))

           return 1;

      

       // recursive call

       return compareTo(s1.substring(1), s2.substring(0));

   }

  

   public static void main(String[] args) {

      

       System.out.println(compareTo(null, null));

       System.out.println(compareTo("a", null));

       System.out.println(compareTo("a", "aa"));

       System.out.println(compareTo(null, "aa"));

       System.out.println(compareTo("aab", "a"));

   }

}

/*

Sample run:

0

1

-1

-1

1

*/