본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.1

[프로그래머스 - JAVA] 문자열 다루기 기본

by 코딩하는 흰둥이 2023. 3. 29.
반응형


  • 내 풀이
class Solution {
    public boolean solution(String s) {
        boolean answer = true;
        
        int a = 0;
        if(s.length() == 4 || s.length() == 6){
            try {
                a = Integer.parseInt(s);
            }catch (Exception e){
                answer = false;
            }
        }
        
        return answer;
    }
}

String.matches 로 풀어보려다가 잘 안돼서 다른분 풀이를 참고해서 풀어보았다

위의 코드로는 answer를 return 시키려고해서 그런지 테스트케이스에서 많은 부분에서 실패하였다

터지는 부분을 이용하다보니 내가 생각하는대로 return answer 가 동작하지 않는거 같다.

 

NumberFormatException 
"문자열" 을 "정수" 형으로 변형시킬때 
"1234" -> 가능
"a234" -> 불가능

 

 

  • 다른 사람 풀이
class Solution {
  public boolean solution(String s) {
      if(s.length() == 4 || s.length() == 6){
          try{
              int x = Integer.parseInt(s);
              return true;
          } catch(NumberFormatException e){
              return false;
          }
      }
      else return false;
  }
}

 

댓글