[백준] 1264. 모음의 개수

c.Hano·2025년 4월 25일

백준

목록 보기
8/8


  1. "#" 이 나오기전까진 while 반복문을 사용하여야한다.
  2. 입력된 string 중에서 모음 (a,e,i,o,u)의 개수를 세어야한다.
  3. 대문자 소문자 상관없이 모음의 개수를 세어야한다.

1번을 만족하기 위해 while 반복문을 작성하고 "#"을 입력받으면 반복문이 종료 된다.

while(true) {
	Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    
    if(str.equals("#"))
    break;
}

2번을 만족하기 위해 조건문을 추가해보자. 입력받은 String을 char단위로 점검해가며 모음일 경우 count가 올라간다.

while(true) {
	Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    
    if(str.equals("#"))
    break;
    
    int count = 0;
   	for(int i = 0 ; i < str.length(); i++) {
    	if(
        str.charAt(i) == 'a' || 
        str.charAt(i) == 'e' ||
        str.charAt(i) == 'o' ||
        str.charAt(i) == 'i' ||
        str.charAt(i) == 'u')
        count ++;
    }
    System.out.println(count);
}

3번을 만족하기 위해 입력받은 String을 소문자(대문자)로 바꾼다.

while(true) {
	Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    str = str.toLowerCase();
    
    if(str.equals("#"))
    break;
    
    int count = 0;
   	for(int i = 0 ; i < str.length(); i++) {
    	if(
        str.charAt(i) == 'a' || 
        str.charAt(i) == 'e' ||
        str.charAt(i) == 'o' ||
        str.charAt(i) == 'i' ||
        str.charAt(i) == 'u') {
        count ++;
        }
    }
    System.out.println(count);
}

정답

import java.util.*;

public class Main {

    public static void main(String[] args) {

        while (true) {
        	Scanner sc = new Scanner(System.in);
            
            String str = sc.nextLine();
            str = str.toLowerCase();
            
            int count = 0;
            if(str.equals("#"))
                break;

            for (int i = 0; i < str.length(); i++) {
                if(
                str.charAt(i)=='a' ||
                str.charAt(i)=='i' ||
                str.charAt(i)=='o' ||
                str.charAt(i)=='u' ||
                str.charAt(i)=='e'){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}
<참고>
  1. .toLowerCase() : 전부 소문자로 만들기
  2. .toUpperCase() : 전부 대문자로 만들기
  3. .charAt() : String 타입을 char형태로 바꿔주는 명령어 () 안의 숫자에 해당하는 글자를 반환한다. ex. String str = "안녕하세요" str.charAt(0) == "안"
profile
꼬질이

0개의 댓글