26.0k views
4 votes
JAVA

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

1 Answer

4 votes

import java.util.Scanner;

public class JavaApplication53 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

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

String txt1 = scan.nextLine();

String txt2 = scan.nextLine();

String newTxt = "";

if (txt1.length() != txt2.length()){

System.out.println("error");

}

else{

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

newTxt += txt1.charAt(i)+""+txt2.charAt(i);

}

}

System.out.println(newTxt);

}

}

I hope this helps!

User Mudassar Shaheen
by
4.8k points