【发布时间】:2013-07-20 06:33:47
【问题描述】:
我编写了一个小程序,它从文件中读取文本并打印文本文件中每个单词的反面。
现在我想尝试有效地查找所有反向的单词是否都是英语词典中的实际单词,并将它们打印为按字符串长度排序的列表,每对出现一次。
这是我目前能写的内容
String word;
String[] reverse;
int wordLength;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
Map<Integer, String> aMap2 = new HashMap<Integer, String>();
String mString = "";
int mInt = 0;
String word;
String[] reverse = new String[1];
int wordLength;
FileInputStream fileIn = new FileInputStream ("example.txt”);
//text in the text file - "what he saw was not part of a trap just a ton of crazy snow"
Scanner scan = new Scanner(fileIn);
Scanner lineScanner;
Scanner wordscanner = null;
String aLine;
String aWord;
while(scan.hasNextLine()){
aLine = scan.nextLine();
lineScanner = new Scanner(aLine);
lineScanner.useDelimiter(",");
word = lineScanner.next();
System.out.println(word);
try{
wordscanner = new Scanner(new File("example.txt"));
} catch(FileNotFoundException x){
x.printStackTrace();
}
while(wordscanner.hasNext()){
Scanner newWord = new Scanner(wordscanner.next());
boolean b;
while(b = newWord.hasNext()){
String foundWord = newWord.next();
wordLength = foundWord.length();
char ch = ' ';
String reverseWord = “";
for(int i = wordLength-1; i >= 0; i--){
ch = foundWord.charAt(i);
//System.out.println(ch);
reverseWord = reverseWord + ch;
}
for(int k = 0; k < reverse.length; k++){
reverse[k] = foundWord + ", " + reverseWord;
mString = reverse[k];
mInt = reverse[k].length();
aMap2.put(mInt, mString);
}
}
}
}
Map<Integer, String> sorted = sortByKeys(aMap2);
System.out.println(sorted);
}
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
List<K> keys = new LinkedList<K>(map.keySet());
Collections.sort(keys);
//LinkedHashMap will keep the keys in the order they are inserted
//which is currently sorted on natural ordering
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(K key: keys){
sortedMap.put(key, map.get(key));
}
return sortedMap;
// http://javarevisited.blogspot.co.uk/2012/12/how-to-sort-hashmap-java-by-key-and-value.html
}
这给了我以下结果
他看到的不是陷阱的一部分,而是一大堆疯狂的雪
{4=a, a, 6=of, fo, 8=ton, not, 10=snow, wons, 12=crazy, yzarc}
现在,我的问题是如何用字典文本文件交叉检查单词的反向(最好是逐个字符)以查看反向单词是否构成有意义的单词?
我环顾四周,看到了一些建议,但找不到能帮助我了解如何解决当前问题的建议。
我曾想过使用二叉搜索树,我的想法是将字典文件加载到二叉树中并搜索树以查看反向单词是否构成现有单词,然后将它们打印出来。但是由于我不明白如何从一个文本文件中获取字符串然后将其与第二个文本文件进行比较,因此我无法继续进行。
最后,请您帮我指出正确的方向,让单词出现在二维数组中,好吗?!我尝试了几次,但它不起作用而且我没有想法:(!
提前致谢。
【问题讨论】:
-
我不明白你输出的这一部分:“10=snow, wons, 12=crazy, yzarc”
-
另外,你如何处理回文?
-
@fge 是输入文本文件中单词相同但相反的单词的结果。我没想到……:哦!谢谢,我会尝试写一个处理回文的方法。
标签: java string compare fileinputstream