Computer Applications

Define a class Anagram to accept two words from the user and check whether they are anagram of each other or not.
An anagram of a word is another word that contains the same characters, only the order of characters is different.
For example, NOTE and TONE are anagram of each other.

Java

Java Iterative Stmts

10 Likes

Answer

import java.util.Scanner;

public class Anagram
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the 2 words to check");
        System.out.print("Enter first word: ");
        String str1 = in.next();
        System.out.print("Enter second word: ");
        String str2 = in.next();
        boolean isAnagram = true;

        String s1 = str1.toLowerCase();
        String s2 = str2.toLowerCase();
        int l1 = s1.length();
        int l2 = s2.length();

        if (l1 != l2) {
            isAnagram = false;
        }
        else {
            int count[] = new int[26];
            for (int i = 0; i < l1; i++) {
                count[s1.charAt(i) - 97]++;
                count[s2.charAt(i) - 97]--;
            }

            for (int i = 0; i < count.length; i++) {
                if (count[i] != 0) {
                    isAnagram = false;
                    break;
                }
            }
        }

        if (isAnagram)
            System.out.println("Anagram");
        else
            System.out.println("Not Anagram");
    }
}

Output

Answered By

2 Likes


Related Questions