package test; import java.io.File; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; public class readIO1 { static int num=0,a=0; static String word[]=new String[1000000]; static int wordnum[]=new int[1000000]; public static void main(String args[]) { try{ String path = "C:\\Users\\lenovo\\Desktop\\Harry Potter and the Sorcerer's Stone.txt"; File file = new File(path); InputStreamReader reader = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(new FileReader(file)); File file2 = new File("Test1.txt"); file2.createNewFile(); BufferedWriter out = new BufferedWriter(new FileWriter(file2)); String s=""; s=br.readLine(); while(s!=null) { s=s.toLowerCase();// 大写转小写 StringTokenizer st = new StringTokenizer(s," ".,?;! :“”‘: "); while(st.hasMoreElements()) { String str =(String)st.nextElement(); for(int j=0;j<num;j++) { if(str.equals(word[j])) { wordnum[j]++; }else a++; } if(a==num) { word[num]=str; wordnum[num]++; num++; } a=0; } s=br.readLine(); } for(int i=0;i<num;i++) { for(int j=i+1;j<num;j++) { if(wordnum[j]>wordnum[i]) { int temp=wordnum[i]; wordnum[i]=wordnum[j]; wordnum[j]=temp; String Temp=word[i]; word[i]=word[j]; word[j]=Temp; } } } for(int i=0;i<num;i++) { System.out.println(word[i]+" "+wordnum[i]); } for(int i=0;i<word.length;i++) { out.write(i+":"+word[i]+" "); out.flush(); } out.close(); }catch(Exception e){ e.printStackTrace(); } } }
实验截图:
实验三是在实验二基础上设定一个全局变量只要单词不相同就存入数组之中其值加一,将输出的循环次数变为设定的那个值即可。