通过input.txt文件读取所有单词,将最长的单词接龙输出到out.txt文件。
package text; import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class word6 { public static void main(String []args) throws IOException { System.out.println("最长单词链为:"); List<Integer> list=new ArrayList<>(); List<Integer> list1=new ArrayList<>(); Scanner scan=new Scanner(System.in); File f = new File("input.txt"); FileInputStream fip = new FileInputStream(f); InputStreamReader reader = new InputStreamReader(fip, "gbk"); StringBuffer sb = new StringBuffer(); while (reader.ready()) { list.add((int) ch((char) reader.read())); // sb.append(ch((char) reader.read())); } // System.out.println(sb.toString()); Object[]a=list.toArray(); for(int i=0;i<list.size();i++) { if((char)(int)a[i]=='@') { list1.add(i); } } reader.close(); fip.close(); Object[]b=list1.toArray(); String []c=new String[9]; c[0]=""; c[1]=""; c[2]=""; c[3]=""; c[4]=""; c[5]=""; c[6]=""; c[7]=""; c[8]=""; int temp=0; for(int i=0;i<list.size();i++) { // if(((char)(int)a[i]==(char)(int)a[(int)b[temp]-1])&&((char)(int)a[i-1]=='@')) // { // for(int k=(int)b[temp]+1;k<(int)b[temp+1];k++) // { // System.out.print((char)(int)a[k]); // } // } if((char)(int)a[i]!='@') { c[temp]+=(char)(int)a[i]; } if((char)(int)a[i]=='@') { temp++; } } int temp1=0; String num=""; for(int i=0;i<9;i++) { if(i==0) { System.out.print(c[0]); num=c[0]; } for(int k=i+1;k<9;k++) { if(c[temp1].charAt(c[temp1].length()-1)==c[k].charAt(0)) { System.out.print("-"+c[k]); num+="-"+c[k]; temp1=k; break; } } } FileWriter fw = null; try { //创建字符输出流 fw = new FileWriter("output.txt"); fw.write("'"+num+"'\r\n"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally块来关闭文件输出流 if (fw != null) { fw.close(); } } } static char ch(char c) { if(!(c>=97&&c<=122)) c+=32; return c; } }
运行结果: