试图让anagram程序工作

时间:2018-02-28 08:20:02

标签: java anagram

我正在为学校做一个项目,要求我通过以下步骤编写一个anagram finder:

  1. 编写一个方法,将字典文件中的单词(只是常规文本文件)读入字符串数组

  2. 编写一个为单词创建字母数组的方法(每个数组应该有26个元素;第k个元素表示单词中第k个字母出现在单词中的次数)

  3. 编写一个比较两个字母数数组以进行完全匹配的方法

  4. 对于词典中的每个单词,生成一个字母计数数组,将其与目标单词的字母计数数组进行比较,如果匹配则打印出单词。

  5. 我的代码编译但没有打印出任何内容,我做错了什么?

    import java.io.*;
    import java.util.Scanner;
    import java.util.List;
    import java.util.ArrayList;
    
    
    public class Anagram 
    {
    
    static String[] words; 
    
    public static String[] readFile(String pathName){          
        List <String> dictionary = new ArrayList<String>();
        try {
            Scanner sc = new Scanner(new File(pathName));            
            while (sc.hasNextLine()){
                dictionary.add(sc.nextLine());
            }                      
    
        }
        catch (FileNotFoundException ex){
            System.out.println("*** Cannot open " + pathName + " ***");
            System.exit(1);        
        }
    
        words = new String[dictionary.size()];
        dictionary.toArray(words);
    
        return words;
    
    }
    
    public static int[] letterCount(String str){
    
        int[] count = new int[26];
    
        for(int i = 0; i< str.length(); i++){
            char ch = str.charAt(i);
            int value = (int) ch;
            if (value >= 97 && value <= 122){
                count[ch - 'a']++;
            }       
        }
    
        return count;
    }
    
    public static boolean sameChar (String firstStr, String secondStr){
    
        if(firstStr.length() != secondStr.length())
            return false;
    
        int[] a = letterCount(firstStr);
        int[] b = letterCount(secondStr);              
        return (a == b);       
    
    }
    
    
    public static void main(String[] args) {
        // TODO code application logic here
    
        System.out.println("Enter target word: ");
        Scanner scanner = new Scanner(System.in);
        String targetWord = scanner.nextLine();
    
        readFile("words.txt");
        for(String word: words) {
            if(sameChar(word, targetWord) == true){
                System.out.println(word + " ");
            }
    
        }   
    }
     }
    

0 个答案:

没有答案
相关问题