Reputation: 13
I am writing a program that takes an input and searches a list of words for any of its anagrams. To do this, it calls a void method search
that prints out 10 anagrams. Here is the code snippet that is causing me trouble:
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a word: ");
String word = input.next();
System.out.println(word);
search(word);
}
This always prints out whatever word you input, but then it stops. When I used the debugger in jGRASP, I noticed that it doesn't even save any value to word
! It also never calls the search
class. The code freezes - it says that it's still running, but it doesn't do anything. However, if I have the user input an integer value after the word, like this:
Scanner input = new Scanner(System.in);
System.out.println("Please enter a word: ");
String word = input.next();
System.out.println(word);
System.out.println("Enter a number: ");
int example = input.nextInt();
search(word);
This will save a value to word
, but not example
, and the code freezes up like before!
EDIT: Here is the search
method. words.txt is a list of words in the same folder.
public static void search(String input) throws Exception
{
Scanner words = new Scanner(new File("words.txt"));
char[] alphabet = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int[] inputLetters = new int[25];
int[] wordLetters = new int[25];
String[] anagrams = new String[10];
int entries = 0;
for(int a = 0; a < input.length(); a++)
{
for(int b = 0; b <= 25; b++)
{
if(input.charAt(a) == alphabet[b])
{
inputLetters[b]++;
}
}
}
while(entries < anagrams.length)
{
while(words.hasNext())
{
String comparison = words.next();
for(int a = 0; a < comparison.length(); a++)
{
for(int b = 0; b < 25; b++)
{
if(comparison.charAt(a) == alphabet[b])
{
wordLetters[b]++;
}
}
}
if(inputLetters == wordLetters)
{
anagrams[entries] = comparison;
entries++;
}
}
}
System.out.println(Arrays.toString(anagrams));
}
Upvotes: 1
Views: 1025
Reputation: 200168
Actually, it's clear as day. You don't need the debugger to find the endless loop.
Here are the key bits of code:
int[] inputLetters = new int[25];
int[] wordLetters = new int[25];
while(entries < anagrams.length)
{
....
if(inputLetters == wordLetters)
{
......
entries++;
}
}
}
Analysis:
entries
, initially 0, is less than anagrams.length
;entries
if inputLetters == wordLetters
;inputLetters
reference can never be equal to the wordLetters
reference. Each refers to its own array;entries
;Upvotes: 3