A class Mix has been defined to mix two words, character by character, in the following manner:
The first character of the first word is followed by the first character of the second word and so on. If the words are of different length, the remaining characters of the longer word are put at the end.
Example: If the first word is “JUMP” and the second word is “STROLL”, then the required word will be “JSUTMRPOLL”
Some of the members of the class are given below:
Class name: Mix
Data members/instance variables:
wrd: to store a word
len: to store the length of the word
Member functions/methods:
Mix(): default constructor to initialize the data members with legal initial values
void feedword(): to accept the word in uppercase
void mix_word(Mix P, Mix Q): mixes the words of objects P and Q as stated above and stores the resultant word in the current object
void display(): displays the word
Specify the class Mix giving the details of the constructor(), void feedword(), void mix_word(Mix, Mix) and void display(). Define the main() function to create objects and call the functions accordingly to enable the task.
import java.util.Scanner;
class Mix{
String wrd;
int len;
public Mix(){
wrd = "";
len = 0;
}
public void feedword(){
Scanner in = new Scanner(System.in);
wrd = in.next().toUpperCase();
len = wrd.length();
}
public void mix_word(Mix P, Mix Q){
int i = 0;
int j = 0;
while(i < P.len && j < Q.len){
wrd += P.wrd.charAt(i) + "" + Q.wrd.charAt(j);
i++;
j++;
}
if(i < P.len)
wrd += P.wrd.substring(i);
if(j < Q.len)
wrd += Q.wrd.substring(j);
}
public void display(){
System.out.println("Word formed = " + wrd);
}
public static void main(String[] args) {
Mix p = new Mix();
System.out.print("First word: ");
p.feedword();
Mix q = new Mix();
System.out.print("Second word: ");
q.feedword();
Mix r = new Mix();
r.mix_word(p, q);
r.display();
}
}
Thanks sir 🙏
My pleasure! Thanks for visiting.