Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java ตรวจสอบสระหรือพยัญชนะ (Vowel or Consonant)


ในบทความนี้ เราจะทำความเข้าใจวิธีตรวจสอบว่าตัวอักษร (character) ที่ป้อนเข้ามาเป็น สระ (Vowel) หรือ พยัญชนะ (Consonant)

สระในภาษาอังกฤษคือ: a, e, i, o, u (ทั้งตัวเล็กและตัวใหญ่) ส่วนตัวอักษรที่เหลือเป็นพยัญชนะ

ตัวอย่าง Input และ Output

Input:

Enter the character : i

Output:

The character : i is a vowel

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร char my_input
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - ใช้เงื่อนไข if ตรวจสอบว่า input เท่ากับ a, e, i, o, u หรือไม่ ถ้าใช่ = สระ มิฉะนั้น = พยัญชนะ
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class VowelAndConsonant {
    public static void main(String[] args) {
        char my_input;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the character : ");
        my_input = my_scanner.next().charAt(0);
        if (my_input == 'a' || my_input == 'e' || my_input == 'i' || my_input == 'o' || my_input == 'u')
            System.out.println("The character : " + my_input + " is a vowel");
        else
            System.out.println("The character : " + my_input + " is a consonant");
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the character : i
The character : i is a vowel

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class VowelAndConsonant {
    public static void main(String[] args) {
        char my_input = 'i';
        System.out.println("The character is defined as :" + my_input);
        if (my_input == 'a' || my_input == 'e' || my_input == 'i' || my_input == 'o' || my_input == 'u')
            System.out.println("The character : " + my_input + " is a vowel");
        else
            System.out.println("The character : " + my_input + " is a consonant");
    }
}

Output

The character is defined as :i
The character : i is a vowel