เริ่มต้นจากการสร้าง Java Project ในที่นี้ผมจะใช้ Eclipse เป็นเครื่องมือในการเขียน โดยจะแบ่งเป็น 2 class คือ class Words และ Class Lab06
- Class Words คลาสนี้ไม่มีอะไรมากครับ แค่เป็นการเขียน Constructor ขึ้นมาเพื่อออบเจ็คไว้ใช้งานครับ ตัวอย่างเช่น ถ้ามีคำว่า dog ซึ่งประโยคนั้นมีจำนวน 3 คำ จะกดหนดดังนี้ Words Dog = new Words(“Dog”, 3);
public class Words { public String Text; public int Count; public Words(String text, int count) { this.Text = text; this.Count = count; } }- Class Lab06 คลาสนี้จะประกอบด้วย 6 เมธอดหลัก คือ
1. เมธอด main ในส่วนนี้จะเป็นเมธอดทั่วไปที่ใช้เรียกเมธอดอื่นๆมาทำงาน
public static void main(String[] args) { String input = "aa a aaa a bb bb b bbbb b c cc ccc cc c c"; splitString = deleteComma(splitInput(input)); result = sortByLength(checkAndCount(splitString)); display(result); }2. เมธอด splitInput ในส่วนนี้จะเป็นการรับประโยคที่เราต้องการจะแบ่ง เพื่อนำมาแบ่งออกเป็นคำๆ
private static String[] splitInput(String input) { String[] output = null; output = input.split(" "); return output; }3. เมธอด deleteComma ในส่วนนี้จะเป็นเมธอดที่เราจะใช้ตัด Comma(,) ที่เราไม่ต้องการออกจากข้อมูลที่ทำการแบ่งแล้วจากเมธอด splitInput
private static String[] deleteComma(String[] splitInput) { String[] output = null; String[] tmp = new String[splitInput.length]; int count = 0; for(int i = 0;i<splitInput.length;i++) { if(!splitInput[i].equals(",")) { tmp[count] = splitInput[i]; count++; } } output = new String[count]; System.arraycopy(tmp, 0, output, 0, count); return output; }4. เมธอด checkAndCount ในส่วนนี้จะเป็นส่วนในการเช็คคำซ้ำและทำการนับจำนวนคำที่ซ้ำ
private static Words[] checkAndCount(String[] splitInput) { Words[] output = null; Words[] tmp = new Words[splitInput.length]; int count = 0; for(int a=0;a<splitInput.length;a++) { int c = 1; for(int b = a+1;b<splitInput.length;b++) { if(splitInput[b].equals(splitInput[a])) { splitInput[b] = ""; c++; } } if(splitInput[a].equals("")) continue; tmp[count] = new Words(splitInput[a], c); count++; } output = new Words[count]; System.arraycopy(tmp, 0, output, 0, count); return output; }5. เมธอด display ในส่วนนี้จะเป็นเมธอดที่ใช้สำหรับการแสดงผล
private static void display(Words[] result) { for(int i = 0;i<result.length;i++) { System.out.println(result[i].Text + ": Count = "+result[i].Count); } }6. เมธอด sortByLength ส่วนเมธอดสุดท้ายนี้ จะใช้สำหรับเรียงคำโดยเรียนจากความยาวน้อยไปหามากโดยใช้ Bubble sort ครับ
private static Words[] sortByLength(Words[] result) { Words tmp; //Sort by Bubble sort for(int a=result.length-1;a>=0;a--) { for(int b = 0;b<a;b++) { if(result[b].Text.length() > result[b+1].Text.length() ) { tmp = result[b]; result[b] = result[b+1]; result[b+1] = tmp; } } } return result; }ผลลัพธ์การรันโปรแกรม