Program to accept two words of same length from user and mix the characters of the two words alternately such that the first word is read left to right and the second word is read from right to left.
Example:
Word 1: “HISTORY”
Word 2: “PHYSICS”
The expected output is “HSICSITSOYRHYP”
Display an appropriate error message if length of two words does not match.
Java
import java.util.*;
public class AltWordMix
{
public static void main(String args[])
{
String str1="",str2="",nstr="";
int l=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the two words of same length:-");
System.out.print("Word 1: ");
str1=sc.next();
System.out.print("Word 2: ");
str2=sc.next();
str1=str1.trim();
str2=str2.trim();
l=str1.length();
if(l!=str2.length())
{
System.out.println("Error! Words are not of same length");
System.exit(1);
}
for(int i=0;i<l;i++)
{
nstr=nstr+str1.charAt(i)+str2.charAt(l-1-i);
}
System.out.println("New string: "+nstr);
}
}Java