Take two String inputs of the same length and merge these by taking one character from each String (starting with the first entered) and alternating. If the Strings are not the same length, the program should print "error".

Sample Run 1:

Enter Strings:
balloon
atrophy
baatlrloopohny
Sample Run 2:

Enter Strings:
terrible
mistake
error

Respuesta :

Answer:

Written in Python

print("Enter strings: ")

str1 = input()

str2 = input()

if len(str1) == len(str2):

     for i in range(0,len(str1)):

           print(str1[i]+str2[i], end='')

else:

     print("Error")

Explanation:

Prompts user for two strings

print("Enter strings: ")

The next two lines get the input strings

str1 = input()

str2 = input()

The following if condition checks if length of both strings are the same

if len(str1) == len(str2):

If yes, this iterates through both strings

     for i in range(0,len(str1)):

This prints the the characters of both strings, one character at a time

           print(str1[i]+str2[i], end='')

If their lengths are not equal, the else condition is executed

else:

     print("Error")

import java.util.Scanner;

public class JavaApplication89 {

   

   public static void main(String[] args) {

       Scanner scan = new Scanner(System.in);

       System.out.println("Enter Strings:");

       String word1 = scan.nextLine();

       String word2 = scan.nextLine();

       String newWord = "";

       if (word1.length() != word2.length()){

           newWord = "error";

       }

       else{

           for(int i = 0; i < word1.length(); i++){

               newWord += word1.charAt(i)+""+word2.charAt(i);

           }

       }

       System.out.println(newWord);

   }

   

}

This is the java solution. I hope this helps!