ภาพรวม
บทความนี้สาธิตวิธีตรวจสอบว่าตัวอักษรแรกใน EditText เป็นพยัญชนะ (Consonant) หรือสระ (Vowel) ในภาษาอังกฤษ
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ป้อนข้อความ" />
<Button
android:id="@+id/buttonPanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ตรวจสอบ" />
</LinearLayout>
ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editQuery = findViewById(R.id.edit_query);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = editQuery.getText().toString().trim().toLowerCase();
if (data.isEmpty()) {
Toast.makeText(MainActivity.this, "กรุณาป้อนข้อความ", Toast.LENGTH_SHORT).show();
return;
}
char firstChar = data.charAt(0);
// ตรวจสอบว่าเป็นตัวอักษรอังกฤษ
if (!Character.isLetter(firstChar)) {
Toast.makeText(MainActivity.this, "ตัวแรกไม่ใช่ตัวอักษร", Toast.LENGTH_SHORT).show();
return;
}
// ตรวจสอบสระ (a, e, i, o, u)
boolean isVowel = "aeiou".indexOf(firstChar) >= 0;
if (isVowel) {
Toast.makeText(MainActivity.this, firstChar + " เป็นสระ (Vowel)", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, firstChar + " เป็นพยัญชนะ (Consonant)", Toast.LENGTH_LONG).show();
}
}
});
}
}
การปรับปรุงจากต้นฉบับ
- ใช้
.toLowerCase()รองรับทั้งตัวพิมพ์เล็กและใหญ่ - ใช้
"aeiou".indexOf()แทนเงื่อนไข OR ยาวๆ - เพิ่ม
Character.isLetter()ตรวจสอบก่อนประมวลผล - ตัดช่องว่างด้วย
.trim()
ขยายสำหรับภาษาไทย
หากต้องการตรวจสอบพยัญชนะ/สระไทย ต้องใช้ logic อื่น เนื่องจากภาษาไทยมีสระนำ/สระตาม/สระบน/สระล่าง และตัวอักษรไทยไม่เรียงลำดับใน Unicode เหมือนอังกฤษ
ทดสอบ
ป้อน "apple" → "a เป็นสระ"
ป้อน "banana" → "b เป็นพยัญชนะ"
ป้อน "123" → "ตัวแรกไม่ใช่ตัวอักษร"