티스토리 뷰

LANGUAGE/JAVA

[JAVA] 문자열 계산기

진심스테이크 2018. 3. 21. 10:03

 

import java.util.Scanner;

public class Calc {
    // 재귀
    public static int calc(String input) {
        int pos;
        // indexof(); - 문자가 없으면 -1반환
        pos = input.indexOf('+'); // +의 위치를 알려줘!
        System.out.println(input);
        if (pos != -1) { // 문자가 있으니까 -1이 아니여야 함
            return calc(input.substring(0, pos)) + calc(input.substring(pos + 1));
        } else {
            pos = input.indexOf('-');
            if (pos != -1) {
                return calc(input.substring(0, pos)) - calc(input.substring(pos + 1));
            } else {
                pos = input.indexOf('*');
                if (pos != -1) {
                    return calc(input.substring(0, pos)) * calc(input.substring(pos + 1));
                } else {
                    pos = input.indexOf('/');
                    if (pos != -1) {
                        return calc(input.substring(0, pos)) / calc(input.substring(pos + 1));
                    }
                }
            }
        }

        String r = input.trim(); // 공백 제거
        if (r == null || r.isEmpty()) // 예외처리
            return 0;

        return Integer.parseInt(r); // r을 int로 변환하여 return
    }

    public static void main(String[] argv) {
        Scanner sc = new Scanner(System.in);
        System.out.print("식 입력 : ");
        String input = sc.next();
        int output = calc(input);

        System.out.println(output);
    }
}

'LANGUAGE > JAVA' 카테고리의 다른 글

[JAVA] STACK / QUEUE  (0) 2018.03.21
[JAVA] CLASS - 클래스  (0) 2018.03.21
[JAVA] 성적 처리  (0) 2018.03.20
[JAVA] ARRAY - 배열  (0) 2018.03.20
[JAVA] THIS  (0) 2018.03.20
댓글