I am trying to create a code in Java, which is going to read two words from anagram.txt file, and see if those two words are anagrams. I am getting an error java.lang.NullPointerException
.
I am not sure what am I doing wrong, so any suggestions? I guess that o2.Anagram()
needs to have some variables, but I want it to call Strings from txt file... I am a beginner, so don't laugh at me :) Thank you!
This is a class that reads from txt file:
import java.io.File;
import java.util.Scanner;
public class Klasa {
public Scanner x;
String s1;
String s2;
public void openFile(){
try{
x = new Scanner(new File("C:\\anagram.txt"));
}
catch(Exception e){
System.out.println("Error");
}
}
public void readFile(){
while (x.hasNext()){
String s1 = x.next();
String s2 = x.next();
}
}
public void closeFile(){
x.close();
}
}
This is a class that should compare two words from anagram.txt
and see if they are anagrams:
import java.util.*;
import java.io.*;
public class isAnagram extends Klasa{
public void Anagram(){
boolean status = true;
if(s1.length() != s2.length()){
status = false;
}
else{
char[] s1Array = s1.toLowerCase().toCharArray();
char[] s2Array = s2.toLowerCase().toCharArray();
Arrays.sort(s1Array);
Arrays.sort(s2Array);
status = Arrays.equals(s1Array, s2Array);
}
//Output
if(status)
{
System.out.println(s1+" and "+s2+" are anagrams");
}
else
{
System.out.println(s1+" and "+s2+" are not anagrams");
}
}
}
And this is main class:
public class mainClass{
public static void main(String[] args){
Klasa o1 = new Klasa();
o1.openFile();
o1.readFile();
o1.closeFile();
isAnagram o2 = new isAnagram();
o2.Anagram();
}
}