java -英语单词接龙

设计思想:

将文件中的单词存入ArrayList数组中,分为前后两个数组,读入单词,经单词字母分解并且通过循环比较单词字母是否相同,相同写入结果文件,不同继续比较,直至找到最大接龙单词长度。

源程序代码:

package 单词接龙;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
public class FineWord
{
    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
    {
        MyFile file = new MyFile();
        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
    {
        MyFile file = new MyFile();
        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)
    {
        FineWord aFineWord = new FineWord();
        try
        {
            aFineWord.fileSplit("d://input1.txt");
            aFineWord.wordWrite(0, "d://output1.txt");
            System.out.println(aFineWord.wordsList);
        } catch (IOException e)
        {
            System.out.println("无此文件");
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
            
        }
    }
}

程序结果:

 

 单个单词无接龙输出首个单词

 总结:这次计算单词链最长长度,使我清楚地认识到将单词长句分解,可以实现很多功能,遇到问题不要慌张,把问题步揍化这样会更加简单。

原文地址:https://www.cnblogs.com/1502762920-com/p/10991770.html