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

โปรแกรม Java นับสระและพยัญชนะในประโยค

ในบทความนี้ เราจะเรียนรู้วิธีนับจำนวนสระ (vowels) และพยัญชนะ (consonants) ในประโยคภาษาอังกฤษใน Java สระคือ a, e, i, o, u ส่วนตัวอักษรอื่นๆ เป็นพยัญชนะ

ตัวอย่างการทำงาน

อินพุต:

Hello, my name is Charlie

เอาต์พุต:

The number of vowels in the statement is: 8
The number of consonants in the statement is: 12

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวนับ: vowels_count, consonants_count และสตริง my_str
  3. รับค่าสตริงจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. แปลงสตริงเป็นตัวเล็กทั้งหมดด้วย toLowerCase()
  5. วนลูป for ตรวจสอบแต่ละตัวอักษร: ถ้าเป็นสระ เพิ่ม vowels_count, ถ้าเป็นตัวอักษร a-z เพิ่ม consonants_count
  6. แสดงผลลัพธ์
  7. จบโปรแกรม

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

import java.util.Scanner;

public class VowelAndConsonants {
    public static void main(String[] args) {
        int vowels_count = 0, consonants_count = 0;
        String my_str;

        Scanner scanner = new Scanner(System.in);
        System.out.println("A scanner object has been defined");
        System.out.print("Enter a statement: ");
        my_str = scanner.nextLine();

        my_str = my_str.toLowerCase();

        for (int i = 0; i < my_str.length(); ++i) {
            char ch = my_str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                ++vowels_count;
            } else if (ch >= 'a' && ch <= 'z') {
                ++consonants_count;
            }
        }

        System.out.println("The number of vowels in the statement is: " + vowels_count);
        System.out.println("The number of consonants in the statement is: " + consonants_count);
    }
}

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

public class VowelAndConsonants {
    public static void main(String[] args) {
        int vowels_count = 0, consonants_count = 0;
        String my_str = "Hello, my name is Charlie";

        System.out.println("The statement is defined as: " + my_str);
        my_str = my_str.toLowerCase();

        for (int i = 0; i < my_str.length(); ++i) {
            char ch = my_str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                ++vowels_count;
            } else if (ch >= 'a' && ch <= 'z') {
                ++consonants_count;
            }
        }

        System.out.println("The number of vowels in the statement is: " + vowels_count);
        System.out.println("The number of consonants in the statement is: " + consonants_count);
    }
}

หมายเหตุ: โค้ดนับเฉพาะตัวอักษรอังกฤษ a-z ไม่นับตัวเลข ช่องว่าง หรือสัญลักษณ์พิเศษ