所以这对大学来说是一个寒假,而我正试图在编码上保持敏锐,所以我只是编写程序和算法的代码,我们只讨论但从未在课堂上编码.无论如何,我今天正在研究的是一个程序,你给计算机一个扰乱的单词,它输出所有可以从这些字母中产生的单词(来自我们给出的EnglishWordList文件).
无论如何,这是我到目前为止的代码:
import java.io.*; import java.util.*; public class ProdFinder { private HashMap<Character,Integer> prodFinder = new HashMap<Character,Integer>(); private HashMap<Integer,LinkedList<String>> findWord = new HashMap<Integer,LinkedList<String>>(); private static final char[] letters = {'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'}; private static final int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101}; public ProdFinder() throws FileNotFoundException { for (int i = 0; i < letters.length; i++) { prodFinder.put(letters[i],primes[i]); } Scanner sc = new Scanner(new File("EnglishWordList.txt")); while (sc.hasNextLine()) { String str = sc.nextLine(); int strProd = findProduct(str); if (findWord.containsKey(strProd)) { LinkedList<String> wordList = findWord.get(strProd); wordList.add(str); findWord.put(strProd,wordList); } else { LinkedList<String> wordList = new LinkedList<String>(); wordList.add(str); findWord.put(strProd,wordList); } } sc.close(); } public int findProduct(String x) { int product = 1; char[] str = x.tocharArray(); for (Character val: str) { product = product*prodFinder.get(val); } return product; } public void descramble(String x) { int prod = findProduct(x); if (findWord.containsKey(prod)) { System.out.println("The words that can be formed from the letters in " + x + " are: " + findWord.get(prod)); } else { System.out.println("No words can be formed from the letters in " + x + "."); } } }
现在,错误起源于我开始将数字的所有主要产品放入我的HashMap的行(试图将每个主要产品映射到其字母乘以该数字的单词的LinkedList.)不知何故,这是抛出异常,如当我注释掉那部分代码并运行findProduct方法时,它可以正常工作,我将它输出为以黄金形式输出lettesr的产品.
有关异常来自何处的任何想法?
编辑:抱歉,堆栈跟踪如下:
Exception in thread "main" java.lang.NullPointerException at ProdFinder.findProduct(ProdFinder.java:44) at ProdFinder.<init>(ProdFinder.java:22) at Descramble.main(Descramble.java:7)
据我所知,当我尝试在str上调用findProd时,错误就出现了:
int strProd = findProduct(str);