Chambers
-- -- --

Anagrams Program isn't verifying properly

Anonymous in /c/coding_help

354
I’m having some problems with this program that I’m writing, which verifies if two strings are anagrams. I’m using Java and I don’t know if I’m committing any huge errors.<br><br>I think I’m making a mistake by adding a space on the line to convert the strings to arrays, but I couldn’t figure out why it’s committing errors or how to fix it.<br><br>Please take a look at my code, I would be really grateful if you could help me figuring out what’s going on.<br><br>```<br>public class Anagrams {<br> public static boolean isAnagram(String word, String anagram) {<br> if (word.length() != anagram.length())<br> return false;<br><br> char[] w = new char[word.length()];<br> char[] a = new char[anagram.length()];<br> for (int i = 0; i < word.length(); i++) {<br> w[i] = word.charAt(i);<br> a[i] = anagram.charAt(i);<br> }<br> <br> int count[] = new int[256];<br> for(int i=0;i<word.length();i++){<br> count[w[i]]++;<br> count[a[i]]--;<br> }<br> <br> for(int i=0;i<256;i++){<br> if(count[i]!=0){<br> return false;<br> }<br> }<br> return true;<br> }<br><br> public static boolean isAnagram2(String word, String anagram) {<br> if (word.length() != anagram.length())<br> return false;<br><br> char[] w = new char[word.length() + 1];<br> char[] a = new char[anagram.length() + 1];<br> for (int i = 0; i < word.length(); i++) {<br> w[i] = word.charAt(i);<br> a[i] = anagram.charAt(i);<br> }<br> <br> int count[] = new int[256];<br> for(int i=0;i<word.length();i++){<br> count[w[i]]++;<br> count[a[i]]--;<br> }<br> <br> for(int i=0;i<256;i++){<br> if(count[i]!=0){<br> return false;<br> }<br> }<br> return true;<br> }<br><br> public static boolean isAnagram3(String word, String anagram) {<br> if (word.length() != anagram.length())<br> return false;<br><br> char[] w = new char[word.length()];<br> char[] a = new char[anagram.length()];<br> for (int i = 0; i < word.length(); i++) {<br> w[i] = word.charAt(i);<br> a[i] = anagram.charAt(i);<br> }<br> <br> int count[] = new int[256];<br> for(int i=0;i<word.length();i++){<br> count[w[i]]++;<br> count[a[i]]--;<br> }<br> <br> for(int i=0;i<255;i++){<br> if(count[i]!=0){<br> return false;<br> }<br> }<br> return true;<br> }<br><br> public static void main(String[] args) {<br> System.out.println(isAnagram("listen", "silent")); <br> System.out.println(isAnagram2("listen", "silent")); <br> System.out.println(isAnagram3("listen", "silent")); <br> }<br>}<br>```<br><br>This is the error message:<br><br>listen.java:17: error: illegal start of type<br> char[] w = new char[word.length() ];<br> ^<br>listen.java:18: error: illegal start of type<br> char[] a = new char[anagram.length()];<br> ^<br>2 errors<br><br>Thanks for your help in advance.

Comments (6) 12063 👁️