Need this in java For this assignment you will write two rec

Need this in java

For this assignment, you will write two recursive functions, both of which will parse any length string that consists of digits and numbers. Both functions should be in the same class and have the following signatures. Make sure you follow the UML exactly, as I will be running unit tests on your submission using this interface.

Write a recursive function that will add up the digits in the string. Example inputs and results:

2. Write a recursive function that will find the largest integer in this string.

input string result
\"1d2d3d\" 6
\"55\" 10
\"xx\" 0

Solution

/**
* @author
*
*/
public class MethodRecursion {
   /**
   * @param args
   */
   public static void main(String[] args) {

       System.out.println(\"sumIt(55): \" + sumIt(\"55\"));
       System.out.println(\"sumIt(1d2d3d): \" + sumIt(\"1d2d3d\"));
       System.out.println(\"sumIt(xx): \" + sumIt(\"xx\"));

       System.out.println(\"findMax(12x8, 0): \" + findMax(\"12x8\", 0));
       System.out.println(\"findMax(012x88, 0): \" + findMax(\"012x88\", 0));

   }

   /**
   * recursive method that will add up the digits in the string
   *
   * @param s
   * @return
   */
   public static int sumIt(String s) {
       if (s.length() == 0)
           return 0;
       else if (Character.isDigit(s.charAt(0))) {

           return Integer.parseInt(s.substring(0, 1))
                   + sumIt(s.substring(1, s.length()));
       } else
           return sumIt(s.substring(1, s.length()));
   }

   /**
   * recursive method that will find the largest integer in this string
   *
   * @param s
   * @param max
   * @return
   */
   public static int findMax(String s, int max) {

       if (s.indexOf(\"x\") == -1) {
           int value = Integer.parseInt(s);
           if (value > max) {
               max = value;

           }
           return max;
       } else {

           int value = Integer.parseInt(s.substring(0, s.indexOf(\"x\")));
           if (value > max) {
               max = value;
           }
           return findMax(s.substring(s.indexOf(\"x\") + 1, s.length()), max);

       }
   }
}

OUTPUT:

sumIt(55): 10
sumIt(1d2d3d): 6
sumIt(xx): 0
findMax(12x8, 0): 12
findMax(012x88, 0): 88

Need this in java For this assignment, you will write two recursive functions, both of which will parse any length string that consists of digits and numbers. B
Need this in java For this assignment, you will write two recursive functions, both of which will parse any length string that consists of digits and numbers. B

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site