这个程序目的在于要将文本中的单词进行录入,同事其中的标点符号要进行舍去,在开始的时候我用Scanner了进行输入,对每个字符串进行录入,先不考虑标点符号的问题,在进行将标点符号的舍去的时候遇到了一些问题,开始我想通过转换为字符数组来进行割舍,遇到了很多问题:数组长度不确定的问题,又通过上网查阅资料知道了java的数组不和c、c++一样有\0终止字符,java没有\0这样的终止字符。所以在最后我想起了java中可以截取子字符串,通过对标点符号位置的记录,再用substing来提取子字符串再来储存到类数组中进行比较,记录。
下面是原代码:
import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.Scanner; public class Scend10_11 { public static void main(String[] args) throws IOException { FindWord [] word; word=new FindWord [100]; word[0]=new FindWord(); word[0].input(word); word[0].show(word); word[0].outfile(word); } } class FindWord{ private String word; //单词 private int num; //单词次数 FindWord(){ word=null; num=1; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } void addnum() { num++; } void outfile(FindWord word[])throws IOException{ //将结果输出到文件中 PrintWriter out =new PrintWriter ("WordTimes.txt"); int i=0; for(i=1;i<100;i++) { if(word[i]!=null) { out.println(word[i].getWord()+"\t"+word[i].getNum()); } } out.flush(); out.close(); } void input(FindWord word[]) throws IOException{ //将文件录入并进行标点符号舍去 Scanner in = new Scanner(Paths.get("word.txt")); String k; while(in.hasNextLine()) { String s=in.next(); compare(s,word); //标点符号的舍去以及对单词额比较和录入方法的电泳 } } private void compare(String str1,FindWord word[]) { int j=0; boolean f=false; char s1[]=str1.toCharArray(); for(int i=0;i<str1.length();i++) { if((s1[i]>=65&&s1[i]<=90)||(s1[i]>=97&&s1[i]<=122)); else {j=i;f=true;} } if(f==true) { if(j==str1.length()-1)change(str1.substring(0,j),word); else{change(str1.substring(0, j),word); change(str1.substring(j+1, str1.length()),word); } } else change(str1,word); //调用change } private void change(String s, FindWord word[]) { //比较单词相同以及储存 int j; boolean bo=false; for(j=0;word[j]!=null;j++) { if(word[j].getWord()!=null&&s.compareTo(word[j].getWord())==0) { word[j].addnum(); bo=true; break; } bo=false; } if(bo==false) { word[j]=new FindWord(); word[j].setWord(s); word[j].setNum(1); } } public void show(FindWord[] word2) { //输出结果 int i=0; for(i=1;i<100;i++) { if(word2[i]!=null) { System.out.println(word2[i].getWord()+"\t"+word2[i].getNum()); } } } }
这个程序我并没有将最后的结果进行排序操作,这项操作以后将会修改这个程序。
原文:https://www.cnblogs.com/huan-ch/p/9775462.html