Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java로 문장 속 모음과 자음 개수 세는 방법

이 글에서는 Java를 사용해 문장 속 모음(vowel)자음(consonant)의 개수를 세는 방법을 알아봅니다. 알파벳 중 'a', 'e', 'i', 'o', 'u'를 모음이라고 부르며, 그 외의 모든 알파벳은 자음으로 분류합니다.

아래는 실제 동작 예시입니다.

입력

Hello, my name is Charlie

출력

문장에 포함된 모음의 개수: 8
문장에 포함된 자음의 개수: 12

알고리즘

  1. 프로그램을 시작합니다.
  2. 정수형 변수 vowels_count(모음 개수), consonants_count(자음 개수)와 문자열 my_str을 선언합니다.
  3. 사용자에게 문자열 입력을 요청하거나 문자열을 직접 정의합니다.
  4. 입력값을 읽어 들입니다.
  5. for 반복문을 실행하며 각 문자가 모음인지 자음인지 판별하고, 해당하는 카운트 변수를 증가시켜 저장합니다.
  6. 결과를 화면에 출력합니다.
  7. 프로그램을 종료합니다.

코드 핵심 포인트

  • toLowerCase(): 대소문자 구분 없이 처리하기 위해 문자열 전체를 소문자로 변환합니다.
  • charAt(i): 반복문 안에서 문자열의 i번째 문자를 하나씩 가져옵니다.
  • 조건 분기: 문자가 모음이면 vowels_count를 증가시키고, 알파벳 소문자 범위(a~z)에 해당하면 consonants_count를 증가시킵니다. 공백이나 특수문자는 카운트에서 제외됩니다.

예제 1: 사용자 입력 받기

이 예제에서는 Scanner 객체를 통해 사용자로부터 문장을 직접 입력받아 처리합니다. 온라인 코딩 도구에서 실시간으로 실행해 볼 수도 있습니다.

import java.util.Scanner;
public class VowelAndConsonents {
   public static void main(String[] args) {
      int vowels_count, consonants_count;
      String my_str;
      vowels_count = 0;
      consonants_count = 0;
      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 vowels in the Consonants is: " + consonants_count);
   }
}

실행 결과

A scanner object has been defined
Enter a statement: Hello, my name is Charlie
The number of vowels in the statement is: 8
The number of vowels in the Consonants is: 12

예제 2: 미리 정의된 문자열 사용하기

이번에는 문자열이 코드 안에서 미리 정의되어 있으며, 그 값을 그대로 가져와 콘솔에 출력합니다.

public class VowelAndConsonents {
   public static void main(String[] args) {
      int vowels_count, consonants_count;
      vowels_count = 0;
      consonants_count = 0;
      String my_str = "Hello, my name is Charie";
      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 vowels in the Consonants is: " + consonants_count);
   }
}

실행 결과

The statement is defined as : Hello, my name is Charie
The number of vowels in the statement is: 8
The number of vowels in the Consonants is: 11

두 예제 모두 같은 로직을 사용하지만, 첫 번째는 사용자 입력을 유동적으로 처리할 수 있고, 두 번째는 고정된 문자열을 빠르게 테스트할 때 유용합니다. 이 코드를 응용하면 한글 텍스트의 초성·중성 분석 등 다양한 문자열 통계 기능으로 확장할 수 있습니다.