大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。最长的定义是:最多单词数量,和单词中字母的数量无关。统一输入文件名称:input1.txtinput2.txt统一输出文件名称:output1.txt

 

设计思想:

1.将文件里的字符串取出来

2.先进行单词分割

3.分割出来的单词字符串,转换为我定义的对象,把字符串的头和尾转换为我定义对象的属性

4.将我默认设立的第一个对象的尾和依次遍历的其他对象的头进行比较,有相同时存入新的字符串中

5.输出其存储的字符串

 

代码实现:

 

package main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

public class jl
{
    public char head;
    public char tail;
public static void main(String[] args) throws IOException
{
InputAction("src/newAnalysis.txt");
}
static String []unUse=new String[] {
        "it",
        "in",
        "to",
        "of",
        "the",
        "and",
        "that",
        "for"
    };
//1.读取文件函数
public static void InputAction(String s) throws IOException
{
    BufferedReader br = new BufferedReader(new FileReader(s));
    StringBuffer sb = new StringBuffer();
    String text = null;
    while ((text = br.readLine()) != null)
    {
        sb.append(text);// 将读取出的字符追加到stringbuffer中
    }
    br.close(); // 关闭读入流
    String str = sb.toString().toLowerCase(); // 将stringBuffer转为字符并转换为小写
    String[] words = str.split("[^(a-zA-Z)]+"); // 非单词的字符来分割,得到所有单词
    jl[] w=new jl[words.length];
    for (int i = 0; i < words.length; i++)
    {
        w[i]=new jl();
        String str1=words[i];
        w[i].head = str1.charAt(0);
        w[i].tail = str1.charAt(words[i].length()-1);
        
    }
    char a=w[0].tail;
    String tx1=new String();
    tx1+=words[0]+' ';
    for (int i = 1; i < w.length; i++)
    {
        if(a==w[i].head) {
            tx1+=words[i]+' ';
            a=w[i].tail;
        }
    }
     try {
         output(tx1,"output.txt");
     } catch (IOException e) {
         // TODO 自动生成的 catch 块
         e.printStackTrace();
     }
    
}



public static void output(String txt,String outfile) throws IOException
{
    File fi=new File(outfile);
    FileOutputStream fop=new FileOutputStream(fi);
    OutputStreamWriter ops=new OutputStreamWriter(fop,"UTF-8");
    ops.append(txt);
    ops.close();
    fop.close();
}
}

 

 

 

实现截图:

 

个人总结:

在本次练习中,我的思路很清晰,然后按照敏捷开发的小目标设立攻克了每一个难点,但是我放了一个我曾经总结过的错误,就是对象数组的使用,必须每一个数组成员都得初始化一下。

posted on 2019-06-08 09:13  生长的力量  阅读(132)  评论(0编辑  收藏  举报