3 of 3
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/
Anagrams for a given input 2.0
This question follows on from :Previous Question
Here is what my reworked code looks like. I neatened it up as much as I could. Changed some of the semantics of it. I also tried to add some faster exit points and checks to prevent errors.
Any further critiques?
/**
* @author :KyleMHB
* Project Number :0002
* Project Name :Anagramatic
* IDE :NETBEANS
* Goal of Project -
* Capture user input, compare to a dictionary file for anagrams,
* output number of matches and the matches.
*/
package anagramatic;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Anagramatic {
public static void main(String[] args) throws FileNotFoundException{
String anagram=getInput("Enter the word you would like to process");
List<String> words=readAnagramsFromFile(anagram, new File("words.txt"));
String output= formatOutput(anagram,words);
displayOutput(output);
}//pvsm
private static String getInput(String prompt) {
String input = JOptionPane.showInputDialog(null,prompt);
return input;
}//getInput
private static List readAnagramsFromFile(String word, File f)
throws FileNotFoundException{
ArrayList<String> anagrams = new ArrayList<>();
try(Scanner s = new Scanner(f)){
while(s.hasNext()){
String candidate=s.next();
if ( (candidate.length()==word.length()) &&
(checkMatch(word,candidate)==true)){
anagrams.add(candidate);
}
}
}
return anagrams;
}//readFile
private static boolean checkMatch(String word, String candidate) {
char[] wordArray = word.toCharArray();
char[] candidateArray = candidate.toCharArray();
if (Arrays.equals(wordArray, candidateArray)){
return false;
}
Arrays.sort(wordArray);
Arrays.sort(candidateArray);
if(Arrays.equals(wordArray, candidateArray)){
return true;
}
/**I did not use an else function for the the below return
*because if (Arrays.equals(wordArray, candidateArray))==true
*it will break on the return*/
return false;
}//match
private static String formatOutput(String original, List<String> words) {
StringBuilder output=new StringBuilder("[ ");
int counter=0;
Iterator<String> wordIt =words.iterator();
while(wordIt.hasNext()){
output.append(wordIt.next());
if(wordIt.hasNext()){
output.append((++counter % 8 == 0)? ",\n" : ", ");
}
}
output.append(" ]");
return ("The Anagram "+original+" has "+words.size()+" matches.\n\nThey are:\n"+output.toString());
}//formatOutput
private static void displayOutput(String output){
JOptionPane.showMessageDialog(null,output);
}//displayOutput
}
Dinocv
- 381
- 1
- 2
- 14
lang-java