일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 이클립스 #이클립스단축키 #자바 #자바단축키
- 숫자정렬
- 버블정렬
- Eclipse
- 자바 #java #이클립스 #eclipse #switch #switch문 #사칙연산 #계산기 #calculator #간단한계산기
- 자바알고리즘
- 자바GUI
- 이클립스
- 자바
- annotation
- Java
- Swing
- 계산기
- 배열정렬
- 오름차순정렬
- 계산기GUI
- MVC
- Spring
- GUI
- 스프링
- 어노테이션
- 내림차순정렬
- 자바 계산기
- 알고리즘
- 버블소트
- Today
- Total
온 코딩
기본 사칙연산 로직 - switch문을 사용한 계산기 로직 본문
계산기 만들기 프로젝트에서 가장 먼저 만들어 본 코드는
사칙연산을 계산하는 아주 간단한 프로그램이다.
1. 변수 선언과 입력값 받기
int num1 = 0;
int num2 = 0;
char operator;
double answer = 0.0;
boolean operatorError = false;
Scanner scanObject = new Scanner(System.in);
System.out.print("Enter the frist number : ");
num1 = scanObject.nextInt();
System.out.print("Enter the scond number : ");
num2 = scanObject.nextInt();
System.out.print("What operation : ");
operator = scanObject.next().charAt(0);
만들려는 프로그램은 입력값 두 개 ( num1 , num2)를 받고 연산자를 받아 결과를 내는 프로그램임으로
num1, num2, operator, answer 네 개의 변수를 각각 유형에 맞게 선언한다.
사용자가 입력한 값을 쓰기 위해 스캐너를 통해 입력 값을 받아 변수에 넣는다.
Scanner는 임포트 하여 활성화 할 수 있음으로 클래스 바깥에
import java.util.*;
를 해준다.
num1,num2의 경우 입력 받은 값을 nextInt()를 통해 int로 변환하여 저장하기 때문에
만일 입력값이 정수가 아닌 경우 프로그램 오류로 종료하게 된다.
operator의 경우, 스캐너로 입력 받은 값을 char로 변경하여 저장하기 때문에 여기서는
연산자가 아닌 다른 값이 입력 되어도 오류가 발생하지 않는다.
operator 오류를 처리하기 위해 operatorError라는 변수를 생성했다.
2. switch를 활용한 사칙연산 수행과 operator 오류 확인
switch (operator) {
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
case '*':
answer = num1 * num2;
break;
case '/':
answer = num1 / num2;
break;
default:
operatorError = true;
System.out.println("Wrong operation!");
}
if (operatorError == true) {
System.out.println("Run again with correct operation.");
} else {
System.out.println("The result is : "+ num1 + " " + operator + " " + num2 + " = " + answer);
}
}
}
operator에 저장 된 값을 통해 사칙 연산을 구현한다.
이 과정에서 만일 operator에 정해진 + , - , * , / 외의 값이 들어가게 되면
default 가 실행되어 operatorError가 true로 변경되며 경고문이 뜨도록 설계했다.
사칙연산 스위치문 구현 자체는 쉬웠지만, operator오류를 처리하는 방법에서 조금 해멨다.
1) 1차 시도 - answer를 구분자로 활용
default:
answer = 0;
System.out.println("Wrong operation!");
}
if (answer == 0) {
System.out.println("Run again with correct operation.");
} else {
System.out.println("The result is : "+ num1 + " " + operator + " " + num2 + " = " + answer);
}
새로운 변수를 쓸 생각은 못하고, answer 값을 특정하여 그 값이 나오면 오류 메세지가 나오도록 설계했다.
이 코드의 문제점은 당연하게도 사칙연산 결과값이 0일 경우에도 오류 메세지가 나온다는 점이다.
2) 2차 시도 - char operatorError 변수를 구분자로 사용
char operatorError = 'E';
//클래스 변수로 선언
default:
answer = operatorError;
System.out.println("Wrong operation!");
}
if (answer == 'E') {
System.out.println("Run again with correct operation.");
} else {
System.out.println("The result is : "+ num1 + " " + operator + " " + num2 + " = " + answer);
}
operatorError라는 변수를 만들어서 'E'로 값을 초기화 시킨 후 default가 생기면 answer값에 operatorError를 넣도록 했다.
이 코드를 짜면서도 answer은 double로 선언하고 operatorError는 char로 선언했는데 어떻게 오류가 없이 돌아가는 것인가 의아했는데, 그 이유는 간단했다. opeartorError에 초기화 된 값 'E'가 유니코드 정수형으로 69이기 때문에 문제가 없었던 것... 그래서 만약 계산 결과 값이 69가 나온다면, 오류가 아님에도 오류메세지가 뜨는 1차 시도와 아주 똑같은 문제가 발생한다.
+ 혹시나 싶어 answer를 강제로 char로 바꾸고 operatorError에 저장하여 플래그로 사용하려했으나 이렇게 하는 경우에도 같은 문제가 발생한다. (operatorError값을 무조건 초기화하여 사용해야 하기 때문)
3) 3차 시도 - boolean operatorError 변수를 플래그로 사용 : 성공
boolean operatorError = false;
//클래스 변수로 선언
default:
operatorError = true;
System.out.println("Wrong operation!");
}
if (operatorError == true) {
System.out.println("Run again with correct operation.");
} else {
System.out.println("The result is : "+ num1 + " " + operator + " " + num2 + " = " + answer);
}
}
앞서 사용했던 operatorError변수를 boolean형으로 바꾸어 operator 오류가 났을 경우를 나타내는 깃발로 사용했다. 사실 이 방법이 오류 검출을 구현하는데 제일 보편적이고 간편한 방법인데 왜 이제야 생각났는지,,,, 깃발을 우선 false 로 초기화 하고, default가 실행되면 true로 바꾸어 깃발이 true인 경우 오류 메세지가 뜨는 로직이다.
3. 전체코드와 실행결과
package calculator;
import java.util.*;
public class BasicCalculator {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
char operator;
double answer = 0.0;
boolean operatorError = false;
Scanner scanObject = new Scanner(System.in);
System.out.print("Enter the frist number : ");
num1 = scanObject.nextInt();
System.out.print("Enter the scond number : ");
num2 = scanObject.nextInt();
System.out.print("What operation : ");
operator = scanObject.next().charAt(0);
switch (operator) {
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
case '*':
answer = num1 * num2;
break;
case '/':
answer = num1 / num2;
break;
default:
operatorError = true;
System.out.println("Wrong operation!");
}
if (operatorError == true) {
System.out.println("Run again with correct operation.");
} else {
System.out.println("The result is : "+ num1 + " " + operator + " " + num2 + " = " + answer);
}
}
}
consloe :
Enter the frist number : 4
Enter the scond number : 5
What operation : f
Wrong operation!
Run again with correct operation.
consloe :
Enter the frist number : 6
Enter the scond number : 78
What operation : *
The result is : 6 * 78 = 468.0
아주 간단하고 기초적인 프로그래밍인데 원하는 방향으로 구현하려다 보니 시간이 좀 오래 걸렸다.
그래도 문제를 발견하고 해결하는 과정에서 요령도 생기고 끈기도 생겼다.
강의에 나오는 코드를 따라하는 것이 아니라 처음으로 혼자 짠 코드여서 뿌듯하다.
'자바_계산기 만들기' 카테고리의 다른 글
계산기_GUI 구현_1차 시도 (0) | 2021.03.04 |
---|