package test7; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * No.222 引き算と足し算 * http://yukicoder.me/problems/no/222 */ public class Question_20_0613 { final static int X_MIN = -10000; final static int Y_MIN = -10000; final static int X_MAX = 10000; final static int Y_MAX = 10000; public static void main(String[] args) { InputStreamReader re = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(re); try { String inputString = br.readLine(); int plusPlace = 0; int minusPlace = 0; int signPlace = 0; String sign = "+"; int result = 0; //算術演算子を探し、場所と符号(ひっくり返したもの)を記録 if (inputString.indexOf("+", 1) > 0){ plusPlace = inputString.indexOf("+", 1); } if (inputString.indexOf("-", 1) > 0) { minusPlace = inputString.indexOf("-", 1); } //数値が0なら大きいほうを、正なら早い方を入れる if (plusPlace == 0 || minusPlace == 0) { signPlace = Math.max(plusPlace, minusPlace); if (minusPlace == 0) { sign = "-"; } } else { signPlace = Math.min(plusPlace, minusPlace); if (Math.min(plusPlace, minusPlace) == plusPlace) { sign = "-"; } } //数値変換(符号考慮) int numX = resultNum(inputString.substring(0, signPlace)); int numY = resultNum(inputString.substring(signPlace + 1, inputString.length())); //数値チェック if (NumJudg(numX, X_MIN, X_MAX) && NumJudg(numY, Y_MIN, Y_MAX)) { //計算 if (sign.equals("+")) { result = numX + numY; } else { result = numX - numY; } System.out.println(result); } else { System.out.println("数値が有効範囲外です"); } } catch (NumberFormatException e){ System.out.println("数字を入力して下さい"); } catch (IOException e) { System.out.println("エラーが発生しました"); } finally { try { re.close(); br.close(); } catch (IOException e) { System.out.println("InputStreamReader、BufferedReaderクローズ中にエラーが発生しました"); } } } /** * 有効値判定 * @param input 判定するもの * @param max 最大値 * @param min 最小値 * @return 範囲内ならtrue,範囲外ならfalseを返す */ private static boolean NumJudg(int input, int min, int max) { Boolean result = false; if (min <= input && input <= max) { result = true; } return result; } /** * 数値に変換して返す(符号も考慮) * @param str * @return 変換した数値 */ private static int resultNum(String str) { int result = 0; if (str.substring(0, 1).equals("-")) { String str1 = str.substring(1, str.length()); int num = Integer.parseInt(str1); result = -num; } else if (str.substring(0, 1).equals("+")) { String str1 = str.substring(1, str.length()); result = Integer.parseInt(str1); } else { result = Integer.parseInt(str); } return result; } }