Java 檔案統計:編寫程式,統計英文文字檔案中的字元數目和單詞數目。程式執行時,輸入要統計的檔案的名稱,程式處理後輸出字元數目和單詞數目
阿新 • • 發佈:2019-02-15
package text6; import java.util.*; import java.io.File; import java.io.FileReader; import javax.swing.JOptionPane; class tongji { public static void main( String[ ] args ) throws Exception { String str = JOptionPane.showInputDialog("請輸入字串(例如:text6.txt):"); File file = new File(str); FileReader reader = new FileReader(file); int length = (int)file.length(); char[] chars = new char[length]; reader.read(chars); reader.close(); String s = String.valueOf(chars); int count = 0; int n = chars.length; for(int i = 0; i < n ; i++) { if(chars[i] >= 'a' && chars[i] <= 'z') { count ++; } } String[ ] words = s.replaceAll( "[^a-zA-Z]+", " " ).trim( ).split( " " ); if ( words.length > 0 ) { TreeSet<Integer> lengths = new TreeSet<Integer>( ); for ( String word: words ) lengths.add( word.length( ) ); JOptionPane.showMessageDialog(null, "字元數:"+String.valueOf(count) +"\n"+"單詞數:"+String.valueOf(words.length)); } else JOptionPane.showMessageDialog(null, "字元數:0"+"\n"+"單詞數:0"); } }