코딩테스트/구름톤 챌린지

[Java] 구름톤 챌린지 1주차 : 합 계산기

이덩우 2023. 8. 16. 11:28

- 문제설명

 

- 해결과정

메인문에서는 누적합계를 저장할 temp 변수를 만들어뒀다.

이후 따로 만든 calculate 메소드를 불러와 누적합 연산을 수행하면 된다.

StringTokenizer를 사용해 연산할 두 숫자와 연산 기호를 획득하는 방식으로 풀이했다.

 

- 솔루션

import java.io.*;
import java.util.*;
class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st;
		int temp = 0;
		int T = Integer.parseInt(br.readLine());
		for(int i = 0; i < T; i++) {
			st = new StringTokenizer(br.readLine());
			temp += calculate(st);
		}
		bw.write(Integer.toString(temp));
		bw.flush();
		bw.close();
	}
	
	private static int calculate(StringTokenizer st) {
		int first = Integer.parseInt(st.nextToken());
		String cal = st.nextToken();
		int second = Integer.parseInt(st.nextToken());
		int result = 0;
		
		if(cal.equals("+")) {
			result = first + second;
		}
		if(cal.equals("-")) {
			result = first - second;
		}
		if(cal.equals("*")) {
			result = first * second;
		}
		if(cal.equals("/")) {
			result = first / second;
		}
		return result;
	}
}