양의 정수 2개 입력 받기
System.out.println("첫 번째 숫자를 입력하세요: ");
int firstNum ;
firstNum = sc.nextInt();
System.out.println("두 번째 숫자를 입력하세요: ");
int secondNum ;
secondNum = sc.nextInt();
콘솔
사칙 연산 기호 입력 받기
.next()
를 통해 String 형식으로 받은 다음 .charAt(0)
을 통해 연산 기호를 입력받는다.System.out.print("사칙연산 기호를 입력하세요: ");
char operation;
operation = sc.next().charAt(0);
콘솔
결과값 출력하기
throw new ArithmeticException();
try{
...
int result = 0;
switch (operation) {
case '+' -> result = firstNum + secondNum;
case '-' -> result = firstNum - secondNum;
case '*' -> result = firstNum * secondNum;
case '/' -> {
if (secondNum == 0) {
throw new ArithmeticException();
}
result = firstNum / secondNum;
}
}
System.out.println("결과: " + result);
} catch ( ArithmeticException e) {
System.out.println("나눗셈 연산에서 분모(두번째 정수)에 0이 입력될 수 없습니다.");
}
<aside> 🔥
result 변수를 선언만 하고 할당은 하지 않았을 경우 에러가 발생했다.
int num1;
num = sc.nextInt();
똑같이 선언만 하고 나중에 할당 하는데, 위 코드와 다르게
int result;
switch(operation) { case ‘+’ : result = a+b; … }
return result;
해당 코드에 에러가 나는 이유는 무엇일까?
✅ Java에서는 지역변수를 선언만 하고 초기화를 보장하지 않으면 컴파일 타임에서 오류를 내기 때문이다.
→ 내 코드에서 해결하는 방법은
</aside>
반복문을 활용한 계산 진행
boolean go = true ;
while ( go ) {
...
System.out.println("더 계산하시겠습니까? (exit 입력 시 종료)");
if ( (sc.next()).equals("exit") ) {
go = false;
}
}
배열 선언 및 연산 결과 저장
int index = 0;
int[] list = new int[10];
while ( go ) {
...
list[index] = result;
index++;
...
}
결과 삭제 및 저장
if( index >= 10 ) {
for (int i = 1; i < 10; i++) {
list[i - 1] = list[i];
}
list[9] = result;
}else {
list[index] = result;
index++;
}
연산 결과가 10개로 고정되지 않고 무한이 저장될 수 있도록 소스 코드를 수정합니다.
저장된 연산 결과 전부 출력
calculate 함수 생성
ArithmeticException
를 throwIllegalArgumentException
를 throwcatch (ArithmeticException e) {
System.*out*.println("나눗셈 연산에서 분모(두번째 정수)에 0이 입력될 수 없습니다.");
} catch ( IllegalArgumentException e) {
System.*out*.println("연산자는 더하기, 빼기, 곱하기, 나눗셈 외 입력될 수 없습니다.");
}
클래스 활용
Calculator calculator = new Calculator();
int result = 0;
result = calculator.calculate(firstNum, secondNum, operation);
System.out.println("결과: " + result);