자바/코드트리

[코드트리] 사칙연산을 이행하는 함수 - 자바(Java)

Jakorithm 2024. 2. 9. 00:45
728x90

문제

https://www.codetree.ai/training-field/search/problems/functions-that-carry-out-four-factor-operations?&utm_source=clipboard&utm_medium=text

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

 

 

각 사칙연산에 해당하는 총 4개의 함수를 작성하고 정수의 연산식이 주어지면 적절한 함수를 호출하여 사칙연산의 연산결과를 출력하는 프로그램을 작성해 보세요.

단, '/'의 결과는 정수 부분만 출력하고, 사칙연산자 이외의 문자가 주어지는 경우는 없다고 가정해도 좋습니다.

 

입력 예시

8 * 13

 

출력 예시

8 * 13 = 104

 

 

코드

첫 번째 줄에 정수 첫 번째 줄에 연산식을 나타내는 x, a, y가 공백으로 구분되어 주어진다.

  • x와 y는 정수 값이며, a는 +, -, *, / 중에서만 주어진다.
  • 1 <= x, y <= 100
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        int x = Integer.parseInt(st.nextToken());
        String operator = st.nextToken();
        int y = Integer.parseInt(st.nextToken());
        
        int result = 0;
        if (operator.equals("+")) {
            result = plus(x, y);
        } else if (operator.equals("-")) {
            result = minus(x, y);
        } else if (operator.equals("*")) {
            result = multiple(x, y);
        } else if (operator.equals("/")) {
            result = divide(x, y);
        }

        System.out.println(x + " " + operator + " " + y + " = " + result);
    }

    private static int plus(int x, int y) {
        return x + y;
    }

    private static int minus(int x, int y) {
        return x - y;
    }

    private static int multiple(int x, int y) {
        return x * y;
    }

    private static int divide(int x, int y) {
        return x / y;
    }
}

 

728x90