Given two words the task is to mix the two words such that first character if the first word is followed by the first character of second word and so on. The words may be of different length so the remaining characters will appear at the end.
Example: “Computer” and “Java”. After mixing the word will be “CJoavmaputer”. Here the mixing of word “Computer” is possible up to letter ‘p’. The remaining characters are followed by it.
Define a class with following specification to perform the above task.
Class Name: MixChar
Member Variables:
str -To store the word.
l – To store the length of the word.
Member Methods:
MixChar() – Default constructor to initialize member variables.
void getInput() – Accept the word and calculate its size.
void mixWords(MixChar X,MixChar Y) – To generate the word explained above.
void displayWord() – To display the generated word.
Invoke all the above methods in main() function using object of the class.
import java.util.*;
public class MixChar
{
String str;int l;
MixChar()
{
str="";
l=0;
}
public void getInput()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a word: ");
str=sc.next();
str=str.trim();
l=str.length();
}
public void mixWords(MixChar X,MixChar Y)
{
l=Math.min(X.l,Y.l);
for(int i=0;i<l;i++)
{
str=str+X.str.charAt(i)+Y.str.charAt(i);
}
if(X.l>Y.l)
{
str=str+X.str.substring(l);
}
else
{
str=str+Y.str.substring(l);
}
}
public void displayWord()
{
System.out.println("Mixed word: "+str);
}
public static void main(String args[])
{
MixChar ob1=new MixChar();
MixChar ob2=new MixChar();
MixChar ob3=new MixChar();
ob1.getInput();
ob2.getInput();
ob3.mixWords(ob1,ob2);
ob3.displayWord();
}
}Java