Java程式計算給定句子中子音的個數


在本文中,我們將使用Java來計算給定句子中子音的個數。為了實現這一點,我們將使用Scanner類獲取使用者輸入,並使用for迴圈遍歷句子中的每個字元。透過將每個字元與母音aeiou進行比較,並忽略空格,我們將識別子音並相應地增加計數器。Scanner類java.util包的一部分,通常用於獲取使用者輸入。

問題陳述

給定一個句子,編寫一個Java程式來計算子音的個數。如下所示:

輸入
Enter a sentence :
Hi hello how are you welcome to tutorialspoint
輸出
Number of consonants in the given sentence is 21

計算給定句子中子音個數的步驟

以下是使用Java計算給定句子中子音個數的步驟:

  • java.util包匯入Scanner類
  • 從使用者處讀取一個句子。
  • 建立一個變數(count)並將其初始化為0。
  • 將句子中的每個字元與字元aeiou進行比較。
  • 如果未匹配,則增加計數。
  • 最後列印計數。

Java程式計算給定句子中子音的個數

下面是使用Java計算給定句子中子音個數的示例:

import java.util.Scanner;
public class CountingConsonants {
    public static void main(String args[]) {
        int count = 0;
        System.out.println("Enter a sentence :");
        Scanner sc = new Scanner(System.in);
        String sentence = sc.nextLine();

        for (int i=0 ; i<sentence.length(); i++) {
            char ch = sentence.charAt(i);
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ) {
                System.out.print("");
            } else if(ch != ' ') {
                count++;
            }
        }
        System.out.println("Number of consonants in the given sentence is "+count);
    }
}

輸出

Enter a sentence :
Hi hello how are you welcome to tutorialspoint
Number of consonants in the given sentence is 21

程式碼解釋

上述程式首先匯入Scanner類並將count變數初始化為0。提示使用者輸入一個句子,使用Scanner.nextLine()讀取。一個for迴圈遍歷句子的每個字元。在迴圈內部,我們使用charAt()獲取每個字元並將其與母音aeiou進行比較。如果字元不是母音且不是空格,則增加count。最後,列印子音的總數。

更新於: 2024年8月8日

9K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.