หมายเหตุสังเกตุบรรทัดที่ระบุว่า D://java_exam/test.txt ตรงนี้ให้เปลี่ยนตามตำแหน่ง file ของท่านเอง
อธิบายโค้ด
-มีการใช้ throws IOException เพราะต้องการลดความยุ่งยากของการใช้ try - catch
-countln คือนับคำตัวสุดท้ายของแต่ละบรรทัด
-count คือนับคำทั้งหมดแต่ละบรรทัดไม่รวมคำสุดท้าย
โปรแกรมสามารถนับคำที่เว้นช่องว่างมากว่า 1 ช่องได้ทั้งด้านหน้าและด้านหลัง
[src]
import java.io.*;
class WordCount
{
public static void main(String args[]) throws IOException
{
int countln=0,count=0;
String out;
FileInputStream fstream = new
FileInputStream("D://java_exam/test.txt");
DataInputStream in =new DataInputStream(fstream);
while (in.available() !=0){
out=in.readLine();
char test[]=out.toCharArray();
System.out.println (out);
for(int c=0;c<test.length;c++){
if(c<test.length-1 ){
if( test[c]!=' ' && test[c+1]==' ' ){
count++;
}
}
}
countln++;
}
in.close();
System.out.println ("Total Word="+(count+ countln));
}
}
[/src]


Reply With Quote
