
내가 생각했을때 문제에서 원하는부분
There is only one line containing two space-separated non-empty strings x and y.
Print the result of the minus operation (x - y) on one Line. If the result is an integer, please print it without the decimal point.
If the result is not a number, please print NaN.
내가 이 문제를 보고 생각해본 부분
BufferedReader를 이용해 한 줄 입력을 받는다.
입력 문자열을 공백을 기준으로 쪼개 x, y에 저장한다.
isNumeric 메서드는 문자열이 오직 숫자(0-9)로만 이루어졌는지 정규 표현식을 통해 검사한다.
두 문자열 모두 숫자일 경우, Double.parseDouble로 실수로 변환 후 뺄셈 연산을 수행한다.
결과가 정수이면 (int) 캐스팅한 정수를 출력한다. (예: 20.0 -> 20)
결과가 정수가 아니면 문제 조건에 따라 "NaN"을 출력한다.
x 또는 y 중 하나라도 숫자가 아니면 바로 "NaN"을 출력한다.
마지막에 리소스 누수를 막기 위해 br.close()로 스트림을 닫는다.
코드로 구현
package baekjoon.baekjoon_33;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// 백준 23343번 문제
public class Main1301 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] inputs = br.readLine().split(" ");
String x = inputs[0];
String y = inputs[1];
if (isNumeric(x) && isNumeric(y)) {
double result = Double.parseDouble(x) - Double.parseDouble(y);
if (result == (int) result) {
System.out.println((int) result);
} else {
System.out.println("NaN");
}
} else {
System.out.println("NaN");
}
br.close();
}
// 숫자로만 이루어졌는지 확인하는 메서드
private static boolean isNumeric(String str) {
return str.matches("\\d+");
}
}
코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.