题目
在words.txt文件中包含了87314个单词,编写Java程序从words文件中读取单词,并输出重复字母对最多的单词,将最多重复字母对的单词写入newwords.txt文件中。例如tooth这个单词有一个重复字母对,committee有三个重复字母对。
流程图
Code
package IO;
import java.io.*;
public class words {
public static void main(String[] args){
File file =new File("words.txt");
File file2=new File("newwords.txt");
word[] words=new word[100000];
int maxx=0;
char[] ch=new char[100000];
try{
FileReader in=new FileReader(file);
FileWriter out=new FileWriter(file2, true);
String str="", last="";
int sum=0, i=0;
while(in.read(ch, 0, 1)!=-1){
String temp=new String(ch, 0, 1);
if(temp.equals("\n")) {
words[i++]=new word(str, sum);
maxx=maxx>sum?maxx:sum;
str = "";
last="";
sum=0;
}else if(temp.equals("\r"))
continue;
else
{
str+=temp;
if(last.equals(temp))
sum++;
last=temp;
}
}
in.close();
for(int j=0;j<i;j++) {
if (words[j].len == maxx) {
out.write(words[j].val+"\n");
}
}
out.close();
}catch(IOException e){
System.out.println(e);
}
}
}
class word{
public word(){val="";len=0;}
word(String a, int b){val=a;len=b;}
String val;
int len;
}
结果展示