What is wrong with my code? (JAVA)


This is
Print alternating characters from two strings (interleaving) using recursion Java
What is wrong with my code?
The comment is what I have to do :

/* Returns a new string consisting of all of the characters of s1
        * and s2 interleaved with each other. For example, if s1 is
        * "Spongebob" and s2 is "Patrick", the
        * function returns the string "SPpaotnrgiecbkob" */
        public static String zipped(String s1, String s2) {
            String result = "";
            String first = "";
            String second = "";
            int longest=0;
            if (s1.length() > s2.length()) {
                longest = s1.length();
                first = s1;
                second = s2;
            if (s2.length() > s1.length()) {
                longest = s2.length();
                first = s2; 
                second = s1;

            for (int i = 0; i < (longest-1); i++) {
                //char a = first.charAt(i);
                result += first.charAt(i);
                //char b = second.charAt(i);
                if (second.charAt(i) == ' ')
                    result += first.charAt(i++);
                    result += second.charAt(i);

            System.out.println("Longest is " + longest);
            return result;

When I do:

String s1 = "miu";
String s2 = "le";

the result became mlie and it missing u which is the last word.


I will only ask few helpful questions because you are close to the correct solution:

  1. Is this really a recursive solution?
  2. What happens if lengths of s1 and s2 are equal?
  3. Why in the for loop there is longest-1?

Answer these questions and you will be able to solve this problem, trust me :slight_smile: