TIL day 49

최병은·2024년 3월 8일
  1. 코딩테스트(햄버거 만들기)
import java.util.Stack;

class Solution {
    public int solution(int[] ingredient) {
        int count = 0;
        Stack<Integer> ing = new Stack<>();

        for (int i = 0; i < ingredient.length; i++) {
            ing.push(ingredient[i]);

            if(ing.size()>=4) {
                if(ing.get(ing.size()-1) == 1
                        && ing.get(ing.size()-2) == 3
                        && ing.get(ing.size()-3) == 2
                        && ing.get(ing.size()-4) == 1) {

                    count++;
                    ing.pop();
                    ing.pop();
                    ing.pop();
                    ing.pop();
                }
            }
        }

        return count;
    }
}

stack은 후입선출식이라 push로 하나씩 저장하고 pop으로 뒤에서부터 하나씩 제거한다.


  1. @ExceptionHandler 에러
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<ApiResponseDto> illegalArgumentExceptionHandler(IllegalArgumentException ex) {
        ApiResponseDto responseDto = new ApiResponseDto(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(
                // HTTP body
                responseDto,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }
 }  
   
@AllArgsConstructor
@Getter // 게터 추가해야함
public class ApiResponseDto {
    private String message;
    private int code;
}

컨트롤러에 GlobalExceptionHandler를 적용시켜봤는데
Faliure in @ExceptionHandler라는 에러가 떴다.
찾아보니 결국엔 ApiResponseDto 클래스에 @Getter를 붙여야 해결이 된다는 결론을 얻었다.
그 이유도 보니까 Jackson 라이브러리를 통해 Json 형태로 반환을 시킬 때 Jackson 라이브러리가 Getter 프로퍼티를 기준으로 ApiResponseDto의 필드들을 가져올 수 있다고 해서 내가 @Getter를 안 달아주니까 에러가 난 것으로 추측된다.

profile
안녕하세요

0개의 댓글