[인프런 워밍업 스터디 클럽] 백엔드 과제2

문제 1

public class CalcResult {
    private int add;
    private int minus;
    private int multiply;

    public CalcResult(int add, int minus, int multiply) {
        this.add = add;
        this.minus = minus;
        this.multiply = multiply;
    }

    public int getAdd() {
        return add;
    }

    public int getMinus() {
        return minus;
    }

    public int getMultiply() {
        return multiply;
    }
}
@GetMapping("/api/v1/calc")
public CalcResult calculate(@RequestParam("num1") int num1, @RequestParam("num2") int num2) {

    int addResult = num1 + num2;
    int minusResult = num1 - num2;
    int multiplyResult = num1 * num2;

    return new CalcResult(addResult, minusResult, multiplyResult);
}

image문제2

public class DayOfTheWeekResponse {
    private String dayOfTheWeek;
    public DayOfTheWeekResponse(String dayOfTheWeek) {
        this.dayOfTheWeek = dayOfTheWeek;
    }

    public String getDayOfTheWeek() {
        return dayOfTheWeek;
    }
}
@GetMapping("/api/v1/day-of-the-week")
public DayOfTheWeekResponse getDayOfTheWeek(@RequestParam("date") String dateString) {
    // 입력된 날짜를 Date 객체로 변환
    Date date = parseDate(dateString);

    // 날짜에서 요일을 계산
    String dayOfWeek = calculateDayOfTheWeek(date);

    // 결과를 DayOfTheWeekResponse 객체로 반환
    return new DayOfTheWeekResponse(dayOfWeek);
}

// 입력된 문자열을 Date 객체로 파싱하는 메서드
private Date parseDate(String dateString) {
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(dateString);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid date format. Please provide date in yyyy-MM-dd format.");
    }
}

// 요일을 계산하는 메서드
private String calculateDayOfTheWeek(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

    // 요일을 문자열로 변환하여 반환
    return new SimpleDateFormat("EEE", Locale.ENGLISH).format(date).toUpperCase();
}

image문제 3

public class AddTotalController {

    @PostMapping("/addTotal")
    public int addTotal(@RequestBody NumbersRequest request) {
        return request.getNumbers().stream().mapToInt(Integer::intValue).sum();
    }
}
public class NumbersRequest {
    private List<Integer> numbers;

    public List<Integer> getNumbers() {
        return numbers;
    }
}

image

채널톡 아이콘