Magic Word Class 11 Theory Year 2019

A class Magic enables the user to accept a word and checks for Magic word. A Magic word is one which has consecutive alphabets within itself at any position.

Example:
MYSTERY has consecutive letters ST and is a Magic word.

AB, PQ, XY, ZA … are some examples of consecutive alphabets.

Some of the members of the class are given below:

Class name: Magic
Data members/instance variables:
str: to store the word.
Member functions/methods:
Magic(): default constructor.
void input(): to accept a word in uppercase.
boolean check(): checks and returns true if the word is a Magic word otherwise returns false.
void display(): displays the word with an appropriate message.

Define the class Magic giving details of the constructor, void input(), boolean check() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.io.*;
class Magic{
    String str;
    public Magic(){
        str = new String();
    }
    public void input()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the word: ");
        str = br.readLine();
        str = str.trim();
        if(str.indexOf(' ') > 0)
            str = str.substring(0, str.indexOf(' '));
        str = str.toUpperCase();
    }
    public boolean check(){
        int len = str.length();
        if(len <= 1)
            return false;
        for(int i = 0; i < str.length() - 1; i++){
            char first = str.charAt(i);
            char last = str.charAt(i + 1);
            if((first + 1 == last) || (first == 'Z' && last == 'A'))
                return true;
        }
        return false;
    }
    public void display(){
        if(check())
            System.out.println(str + " is a Magic word.");
        else
            System.out.println(str + " is NOT a Magic Word.");
    }
    public static void main(String args[])throws IOException{
        Magic obj = new Magic();
        obj.input();
        obj.display();
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.