Hey guys, I've been working on this project for a couple days now and I can't get it right. It's due in 5 hours :\
Okay, so the assignment is to code a "weak" anagram tester - the program should take two Strings in and print YES if they are weak anagrams of each other, and NO if otherwise.
My teacher is defining a "weak anagram" as any phrases which use the same letters. Punctuation and spaces ignored, this program should check if the two words share the same characters.
For example,
ABC!$ | abc = YES
aaabbbccc | abc = YES
abcd | abc = NO
etc... You get the point.
My professor suggested that we create two boolean arrays, which I have done. If each element of the arrays corresponds to a different char, I want to make the elements true which correspond to characters in the entered phrases. However, I am having trouble doing so.
Here is my code:
import java.util.*; public class WeakAn2Tester{ public static void main (String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Enter two words or phrases"); String firstLine = scan.nextLine(); String secondLine = scan.nextLine(); WeakAnTester2 ana = new WeakAnTester2(firstLine, secondLine); ana.False(); ana.Sort(); ana.isAnagram(); } }
and
public class WeakAnTester2{ int f; int g; boolean[] firstArray = new boolean[26]; boolean[] secondArray = new boolean[26]; String one; String two; public WeakAnTester2(String line1, String line2){ one = line1; two = line2; } public void False(){ // Sets each element of the two arrays to false for (int j=0; j<26; j++){ firstArray[j] = false; secondArray[j] = false; } } public void Sort(){ // Entries to lowercase, remove punctuation. one = one.toLowerCase().replaceAll("\\W", ""); two = two.toLowerCase().replaceAll("\\W", ""); // Sets true the values of firstArray & second Array which correspond to characters of entries // These loops are not doing anything at the moment, but I don't know why for(int k=0; k<one.length(); k++){ for(int j=0; j<26; j++){ if (one.charAt(k) == (char)('a'+j)); firstArray[j] = true; } } for(int k=0; k<two.length(); k++){ for (int j=0; j<26; j++){ if (two.charAt(k) == (char)('a'+j)); secondArray[j] = true; } } } public void isAnagram(){ for (boolean b : firstArray){ if (b == true){ f++; } } for (boolean b : secondArray){ if (b == true){ g++; } } if (g == f) System.out.println("YES"); else System.out.println("NO"); } }
Right now, the code always returns "YES" because the ints g and f are always 0.
I really appreciate anyone who takes the time to read all of this and help me out!