软件工程课堂十一(计算最长英语单词链)

第一步:完成从文件读取英文文章和存入文件中

第二步:通过数组的形式去存入这篇文章的每个单词

第三步:保证每个单词是不为重复的单词

第四步:将这些单词进行首位相连

第五步:使首位相连的单词前一个最后一个字母和后一个首字母是相同的

以上是我自己在做这道题前的大概的一个思路,但是在实际完成的时候我值完成

了从文件读取文章和存入文件这两个部分,以下是代码:

package Eg;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Eg {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D:\input1.txt");// 读取文件
        if (!file.exists()) {// 如果文件打不开或不存在则提示错误
            System.out.println("文件不存在");
            return;
        }
        String[] strs=new String[1000];
        Scanner x = new Scanner(file);
        int i=0;
        while(x.hasNextLine()) {
            strs[i]=x.nextLine();
            i++;
        }
        String sentence = "";
        String word="";
        for(int m=0;m<i;m++) {
            sentence = strs[m];
            word = sentence;
            for(int j=m+1;j<i;j++) {
                if(strs[j].toLowerCase().subSequence(0, 1).equals(word.toLowerCase().subSequence(word.length()-1, word.length()))) {
                    word = strs[j];
                    sentence+="-"+word;
                }
            }
            if(sentence.indexOf("-")!=-1) {
                System.out.println(sentence);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/dinghaisheng/p/11071304.html