백준 5622번 자바(JAVA)

SuYeong·2022년 1월 19일
1

백준 5622번 자바(JAVA)

https://www.acmicpc.net/problem/5622

위의 문제를 풀어보도록 하겠다.

문제

  • 1을 누를때는 2초, 그 다음의 숫자를 누를 때는 1과의 거리에 따라 1초씩 추가시간이 붙는다

  • 각 문자는 숫자번호에 대응된다

  • 1 : 1
    ABC : 2
    DEF : 3
    GHI : 4
    JKL : 5
    MNO : 6
    PQRS : 7
    TUV : 8
    WXYZ : 9
    OPERATOR : 0

테스트 케이스 분석

  • WA : 10 + 3 = 13

  • UNUCIC : 9 + 7 + 9 + 3 + 5 + 3 = 36

구현 과정

  1. 문자열 입력 받기
  2. length만큼 for문 돌면서 각 문자 추출
  3. 추출한 문자를 선택하는데에 드는 시간 구하기
  4. 드는 시간의 합 구하기

코드

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String str = scanner.nextLine();
        char charAt;
        int totalTime = 0;
        int tmp;

        try {
            for (int i = 0; i < str.length(); i++) {
                charAt = str.charAt(i);
                tmp = test(charAt);
                //System.out.println(tmp);
                totalTime += tmp;
            }
            System.out.println(totalTime);

        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }

    }
    public static int test(char charAt) throws RuntimeException {
        int time = 2;
        if(charAt == 'A' || charAt == 'B' || charAt == 'C')
            time+=1;
        else if(charAt == 'D' || charAt == 'E' || charAt == 'F')
            time+=2;
        else if(charAt == 'G' || charAt == 'H' || charAt == 'I')
            time+=3;
        else if(charAt == 'J' || charAt == 'K' || charAt == 'L')
            time+=4;
        else if(charAt == 'M' || charAt == 'N' || charAt == 'O')
            time+=5;
        else if(charAt == 'P' || charAt == 'Q' || charAt == 'R' || charAt == 'S')
            time+=6;
        else if(charAt == 'T' || charAt == 'U' || charAt == 'V')
            time+=7;
        else if(charAt == 'W' || charAt == 'X' || charAt == 'Y' || charAt == 'Z')
            time+=8;
        else
            throw new RuntimeException("대문자 영어 문자열을 입력해야 합니다.");

        return time;
    }
}

고찰

  • 각 문자의 경우를 모두 조건문을 돌면서 만들었는데 이 점이 굉장히 아쉬웠다.
    아스키코드로 해보려고 했는데, 각 문자들이 숫자에 3개씩 할당되어 있지 않아서 원하는 것처럼 깔끔한 코드가 안나온다.

  • 예외처리하는 코드를 사용해보고 싶어서, 유효성 검사를 예외처리로 만들어보았다.

profile
안녕하세요

1개의 댓글

comment-user-thumbnail
2022년 1월 26일

백준이 뭐에요?

답글 달기