Mix Words ISC Computer Science 2020 Theory

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 in "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 mixWord(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 details of the constructor, void feedWord(), void mixWord(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 = new String();
        len = 0;
    }
    public void feedWord(){
        Scanner in = new Scanner(System.in);
        wrd = in.next().toUpperCase();
        len = wrd.length();
    }
    public void mixWord(Mix p, Mix q){
        int i = 0;
        while(i < p.len && i < q.len){
            this.wrd += p.wrd.charAt(i);
            this.wrd += q.wrd.charAt(i);
            i++;
        }
        if(i < p.len)
            this.wrd += p.wrd.substring(i);
        if(i < q.len)
            this.wrd += q.wrd.substring(i);
    }
    public void display(){
        System.out.println(wrd);
    }
    public static void main(String args[]){
        Mix a = new Mix();
        System.out.print("Enter first word: ");
        a.feedWord();
        Mix b = new Mix();
        System.out.print("Enter second word: ");
        b.feedWord();
        Mix c = new Mix();
        c.mixWord(a, b);
        c.display();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory