0

If I enter anagram strings like "act" and "cat" then it gives this error: Exception in thread "main" java.lang.NullPointerException at examples.Anagram.main(Anagram.java:20)


import java.util.Scanner;

public class Anagram {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the String 1:");
        String str1 = sc.nextLine();
        System.out.print("Enter the String 2:");
        String str2 = sc.nextLine();
        Boolean isAnagram = false;
        Boolean[] isVisited = new Boolean[str1.length()];

        if(str1.length() == str2.length()){
            for(int i=0;i<str1.length();i++){
                char c = str1.charAt(i);
                isAnagram = false;
                for(int j=0;j<str2.length();j++) {
                    if (c == str2.charAt(j) && !isVisited[j]) {
                        isAnagram = true;
                        isVisited[j] = true;
                        break;
                    }
                    if (!isAnagram) {
                        break;
                    }
                }
            }
        }
        if(isAnagram){
            System.out.print("Anagram:)");
        }else{
            System.out.print("Not a Anagram:(");
        }
    }
}
Khushal Abrol
  • 13
  • 1
  • 2
  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Amongalen Aug 04 '20 at 09:31
  • 1
    Just an extra tip - your problem is with `isVisited` - it is initialized with `null`s. – Amongalen Aug 04 '20 at 09:35
  • 1
    Perhaps you mean to have a `boolean` array instead of `Boolean`. `boolean` values are default false; but `Boolean` values are default null. – khelwood Aug 04 '20 at 09:36

0 Answers0