6. แยกย่อย

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 6-7  โปรแกรมนับจำนวนวรรณยุกต์ในพจนานุกรม (ปรับจากรหัสที่ 5-13)
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
// โปรแกรมนับจำนวนวรรณยุกต์ในพจนานุกรม 
public class ToneCount {
  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(new File("c:/java101/riwords.txt"));
    int c1 = 0, c2 = 0, c3 = 0, c4 = 0;
    String t1 = "่";  // ไม้เอก 
    String t2 = "้";  // ไม้โท 
    String t3 = "๊";  // ไม้ตรี 
    String t4 = "๋";  // ไม้จัตวา 
    while (in.hasNext()) {
      String line = in.nextLine();
      line = line.trim();        
      if ( line.length()>0 && !"#".equals(line.substring(0,1)) ) {
        c1 += countTone(line, t1);
        c2 += countTone(line, t2);
        c3 += countTone(line, t3);
        c4 += countTone(line, t4);
      }
    }
    System.out.println("ไม้เอกมี\t " + c1 + " ตัว");
    System.out.println("ไม้โทมี\t " + c2 + " ตัว");
    System.out.println("ไม้ตรีมี\t " + c3 + " ตัว");
    System.out.println("ไม้จัตวามี\t " + c4 + " ตัว");
  }
  // countTone คืนจำนวน tone ที่ปรากฏใน word
  public static int countTone(String word, String tone) {
    int k = -1, count = 0;
    while ((k=word.indexOf(tone, k+1)) >= 0) {
      count++;
    }
    return count;
  }
}
©2009 S.Prasitjutrakul