백준 1541번

! 주의 !

(주석 부분 참고)

String temp[] = a.split("\\+");와 같이 ‘+’앞에 역슬래시 두 개를 붙여줘야 하는 이유

+는 문자 클래스 안이든 밖이든 항상 "앞의 문자가 1개 이상 반복됨" 이라는 메타 문자이기 때문에 다음과 같은 메타문자의 의미로 해석되어 앞에 반복 대상이 없기 때문에 오류가 발생하게 된다.

import java.util.Scanner;
public class Practice36 {//백준 P1541

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		String input = sc.nextLine();
		String[] str = input.split("-");
		
		int answer = 0;
		for(int i = 0; i < str.length; i++) {
			int temp = plus_sum(str[i]);
			if(i == 0)
				answer = answer + temp;
			else
				answer = answer - temp;
		}
		System.out.println(answer);
		
		sc.close();
	}
	static int plus_sum(String a) {
		int sum = 0;
		
		String temp[] = a.split("\\\\+"); //+앞에 역슬래시 두개 붙여줘야함
		for(int i = 0; i < temp.length; i++) {
			sum += Integer.parseInt(temp[i]);
		}
		return sum;
	}

}