大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。最长的定义是:最多单词数量,和单词中字母的数量无关。
统一输入文件名称:input1.txt, input2.txt
统一输出文件名称:output1.txt,output2.txt
程序需要考虑下列异常状况:
例如,文件不存在,你的程序会崩溃么,还是能优雅地退出并给用户提示信息?
如果文件没有任何单词、只有一个单词、没有可以首尾相连的单词,程序应该如何输出?
如果输入文件有一万个单词,你的程序能多快输出结果?
a
package a; import java.io.*; import java.nio.file.Paths; import java.util.Scanner; public class a { @SuppressWarnings("resource") public String get(String path) throws IOException { Scanner in = null; String File = ""; in = new Scanner(Paths.get(path)); while (in.hasNextLine()) { File += in.nextLine(); } return File; } public BufferedWriter put(String path) { try { FileWriter f = null; BufferedWriter bf = null; try { f = new FileWriter(path); bf = new BufferedWriter(f); } catch (IOException e) { e.printStackTrace(); } return bf; } catch (Exception e) { e.printStackTrace(); } return null; } }
b
package b; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; import a.a; public class b { public ArrayList<String> words = new ArrayList<>(); public ArrayList<String> wordsList = new ArrayList<>(); public boolean compare(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); return (a.substring(a.length() - 1).equals(b.substring(0, 1))); } public void fileSplit(String path) throws Exception { a file = new a(); String theFileString = file.get(path); if (theFileString == null) { return; } if (theFileString.equals("")) { throw new Exception("空文件"); } for (String word : theFileString.split("\,|\.| |\(|\)|\;|\:|"|\?|\!|\'| |\、|\”|\“")) { if (!word.equals("")) { words.add(word); } } if (words.size() <= 1) { throw new Exception("文件内单词过少(只有" + words.size() + "个词)"); } } public void wordWrite(int index, String path) throws Exception { a file = new a(); BufferedWriter bf = file.put(path); wordsList.add(words.get(index)); try { for (String string : words) { if (compare(wordsList.get(wordsList.size() - 1), string)) { wordsList.add(string); bf.append(string); bf.newLine(); } } bf.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if (wordsList.size() <= 1) { throw new Exception("文件内无单词链"); } } public static void main(String[] args) { b aFineWord = new b(); try { aFineWord.fileSplit("D:/input.txt"); aFineWord.wordWrite(0, "D:/output.txt"); System.out.println(aFineWord.wordsList); } catch (IOException e) { System.out.println("无此文件"); } catch (Exception e) { System.out.println(e.getMessage()); } } }
程序截图
这是在网上借鉴的别人的的代码,能够基本完成要求,但还有些小问题,对与这个代码也不是很懂,有时间再细细研究。