我无法编译我的程序。 我正在尝试做的是让程序打印出所有混乱的单词,并在旁边打印出可以从它制作的字典单词。 我相信这是我嵌套循环的方式上的错误,但我无法弄清楚。 有人能帮我一把吗?
public static void main(String[] args) throws Exception
{
if (args.length < 2) die("Must give name of two input files on cmd line.");
BufferedReader dictionaryFile = new BufferedReader( new FileReader( args[0] ));
BufferedReader jumbleFile = new BufferedReader( new FileReader(args[0] ));
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> jumbleWords = new ArrayList<String>();
ArrayList<String> dictionaryWords = new ArrayList<String>();
ArrayList<String> keysList = new ArrayList<String>();
while(jumbleFile.ready())
{
String jWord=jumbleFile.readLine();
jumbleWords.add(jWord);
}
jumbleFile.close();
Collections.sort(jumbleWords);
while(dictionaryFile.ready())
{
String dWord= dictionaryFile.readLine();
String dictWord= toCanonical(dWord);
if(map.containsKey(dictWord))
{
map.get(dictWord);
map.put(dWord, map.get(dictWord));
}
else
{
ArrayList<String> dictionaryWords2 = new ArrayList<String>();
dictionaryWords2.add(dWord);
map.put(dictWord, dictionaryWords2);
}
for( String i : map.keySet())
{
keysList.add(i);
}
Collections.sort(keysList);
for (String key : keysList)
{
System.out.print(key);
String toCanJWord= toCanonical(key);
if(map.containsKey(toCanJWord))
{
map.get(toCanJWord);
Collections.sort(map.get(toCanJWord));
for(map.get(toCanJWord))
{
System.out.print(toCanJWord);
}
}
System.out.println();
}
private static String toCanonical( String word )
{
char[] letters = word.toCharArray();
Arrays.sort(letters);
return new String(letters);
}
private static void die( String errmsg )
{
System.out.println( "nFATAL ERROR: " + errmsg + "n" );
System.exit(0);
}
}`
你有几个问题。首先,您在这里for loop
末尾缺少一个}
:
for (String key : keysList)
{
System.out.print(key);
String toCanJWord = toCanonical(key);
if(map.containsKey(toCanJWord))
{
map.get(toCanJWord);
Collections.sort(map.get(toCanJWord));
//this isn't correct. Not sure what you are trying to do here
//but this is why it won't compile
for(map.get(toCanJWord))
{
System.out.print(toCanJWord);
}
}
}//missing this closing bracket
您的 for 循环也存在问题,请参阅评论。
你的 for 循环是错误的:
for(map.get(toCanJWord))
{
System.out.print(toCanJWord);
}
它需要采用以下格式:
for(String wordToPrint : map.get(toCanJWord))
{
System.out.print(wordToPrint );
}