Hello Stack Overflow Community. I developed a simple Java program to detect whether or not a word entered by the user is an Anagram. I do not receive the expected output based on the boolean value. Any ideas or suggestions are appreciated.
Note: This code does not include any methods or class functions that would make this a rather simple solution. Please work with the code below. Thank you!
import javax.swing.*;
public class Anagram
{
public static String word = " ";
public static boolean match = false;
public static void main(String[] args)
{
//Prompt the User for a Word
word = JOptionPane.showInputDialog("Please Enter A Word");
//Break the Word into an Array
String[] anagram = new String[word.length()];
for(int i = 0; i < word.length(); i++)
{
anagram[i] = Character.toString(word.charAt(i));
JOptionPane.showMessageDialog(null, anagram[i]);
}
//Create a duplicate Array
String[] anagram2 = new String[word.length()];
for(int i = word.length() - 1; i >= 0; i--)
{
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
//Do a search on each letter
for (int i = 0; i < anagram.length && i < anagram2.length; i++)
{
if(anagram.length == anagram2.length)
{
if(anagram[i].toLowerCase() == anagram2[i].toLowerCase())
{
match = true;
}
else
{
match = false;
}
}
else
{
JOptionPane.showMessageDialog(null, "There is a mismatch");
match = false;
}
}
//Prompt the user with the result
if(match == true)
{
JOptionPane.showMessageDialog(null, "Your Word is a Anagram!");
}
else if(match == false)
{
JOptionPane.showMessageDialog(null, "Your Word is NOT a Anagram!");
}
}
}
Assuming you mean palindrome:
Your code doesn't actually reverse the String.
for(int i = word.length() - 1; i >= 0; i--) {
anagram2[i] = anagram[i];
JOptionPane.showMessageDialog(null, anagram2[i]);
}
This copies anagram into anagram2 without reversing it - it does go through it from back to front, but the result will be the same.
You need to do something like
for (int i = 0; i < word.length(); i++) {
anagram2[word.length() - i - 1] = anagram[i];
}
However, there really is no need to create the anagram and anagram2 arrays in the first place, you can just iterate through the String's data itself using charAt.
boolean match = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
match = false;
break;
}
}
Side note, you shouldn't declare word
and match
as static variables, keeping them local in main()
will do.