KnowledgeBoat Logo

Computer Applications

Write a program in Java to accept a word. Pass it to a method magic(String str). The method checks the string for the presence of consecutive letters. If two letters are consecutive at any position then the method prints "It is a magic string", otherwise it prints "It is not a magic string".

Sample Input: computer
Sample Output: It is not a magic string
Sample Input: DELHI
Sample Output: It is a magic string

Java

User Defined Methods

58 Likes

Answer

import java.util.Scanner;

public class KboatMagicString
{
    public void magic(String str) {
        
        boolean isMagicStr = false;
        String t = str.toUpperCase();
        int len = t.length();
        
        for (int i = 0; i < len - 1; i++) {
            if (t.charAt(i) + 1 == t.charAt(i + 1)) {
                isMagicStr = true;
                break;
            }
        }

        if (isMagicStr)
            System.out.println("It is a magic string");
        else
            System.out.println("It is not a magic string");
    }
    
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter word: ");
        String word = in.nextLine();
        
        KboatMagicString obj = new KboatMagicString();
        obj.magic(word);
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program in Java to accept a word. Pass it to a function magic(String str). The function checks the string for the presence of consecutive letters. If two letters are consecutive at any position then the function prints "It is a magic string", otherwise it prints "It is not a magic string". Sample Input: computer Sample Output: It is not a magic string Sample Input: DELHI Sample Output: It is a magic string

Answered By

26 Likes


Related Questions