오늘은 웹 검색이나 AI의 도움없이 정수 계산기를 만들어보는 연습과정을 거쳤다.
Scanner sc = new Scanner(System.in);
while(true) { //원할때까지 계산 반복
System.out.print("Type first Number ");
int firstNum = sc.nextInt();
System.out.print("Type calculator symbols ");
char symbols = sc.next().charAt(0);
System.out.print("Type second Number ");
int secondNum = sc.nextInt();
cal(firstNum, symbols, secondNum); //계산함수
System.out.println("Do you want cal again? type num '1'");
int keepCal = sc.nextInt();
if(keepCal != 1) break;
}
첫번째로, Scanner 객체를 생성하여 사용자가 원하는 값을 받을 수 있게 설정했다.
그 뒤, 입력받은 값을 int형으로 변환시키기 위해 nextInt()를 사용하여 정수를 입력받고,
사칙연산 부호는 scanner에서 char타입으로 입력받을수 없기 떄문에 next를 통해 String으로 입력받고, charAt(0)을 사용하여 char형태로 변환시켰다.
또한 While문을 사용하여 1을 입력하면 계속 계산기를 동작할 수 있게 구현했다.
static class Result{
private int result;
public int getResult(){
return result;
}
public void setResult(int result){
this.result = result;
}
}
계산 결과값을 외부에서 접근할수 없도록 private로 설정하고, Getter와 Setter 매서드를 활용하여 값을 수정 및 조회할 수 있게 구현했다.
public static void cal(int a, char c, int b){
result result = new result();
if(c == '+'){
result.setResult(a+b);
System.out.println("The result is " + result.getResult());
}
else if(c == '-'){
result.setResult(a-b);
System.out.println("The result is " + result.getResult());
}
else if(c == '*'){
result.setResult(a*b);
System.out.println("The result is " + result.getResult());
}
else if(c == '%'){
if(b == 0){
System.out.println("Can't div with 0");
return;
}
result.setResult(a%b);
System.out.println("The result is " + result.getResult());
}
else if(c == '/'){
if(b == 0){
System.out.println("Can't div with 0");
return;
}
result.setResult(a/b);
System.out.println("The result is " + result.getResult());
}
else{
System.out.println("plz type symbols (+, -, %, *, /)");
}
}
if문과 비교 연산자를 활용하여 어떤 계산을 수행할건지 결정할 수 있게 구현했다.
또한, 결과값을 Setter를 통해 result 객체에 저장하고, Getter을 이용하여 result 객체에 저장된 값을 출력하도록 만들었다.
또한 0으로 나누기를 시도할경우 오류가 발생하기 때문에 조건문을 사용하여 예외처리를 하였다.
아무래도 웹 검색이나 AI의 도움없이 만들었던것이라 값을 입력받는 것부터 어려움을 겪었다.
처음엔 입력받을 값을
Scanner firstNum = new Scanner();
Scanner sybols = new Scanner();
Scanner secondNum = new Scanner();
로 설정하였다.
public static void cal(int a, char c, int b)
하지만, 부분에서 계속 오류가 발생하였다.
그래서 원인을 고민해보니, 입력받은 객체의 타입은 Scanner인데 이를 int와 char타입으로 참조하려 하니 오류가 발생한 것이었다.
이를 통해 객체 타입과 변수 타입에 대해 더욱 깊이 이해할 수 있었다.
두번째로는 Setter 구현 과정에서 어려움을 겪었다.
결과값을 private 타입으로 선언하는 것 까지는 기억하고 있었지만,
Setter매서드의 내부 코드인
this.result = result;
구문이 잘 기억나지 않아 잠시 해맸다.
현재 작성한 코드는 값을 int타입으로 받아들이기 때문에 정수계산만 가능하다.
이를 double타입으로 입력받아 실수도 계산할 수 있도록 개선할 예정이다.
또한, 현재는 조건문을 통해 오류를 처리하고있다.
이를 예외 처리를 활용하여 오류를 더욱 효율적으로 처리할 수 있도록 개선할 예정이다.
마지막으로, 현재는 단순히 계산결과만 출력하고 있지만, 추후에는 result1, result2처럼 계산 결과를 저장하여 이를 활용한 추가연산이나 삭제, 특정 값 이상의 결과만 출력하는 등의 추가 기능을 개발할 예정이다.
package org.example;
import java.util.Scanner;
public class Main {
static class Result{ //getter, setter 클래스
private int result;
public int getResult(){
return result;
}
public void setResult(int result){
this.result = result;
}
}
public static void cal(int a, char c, int b){ //사칙연산 구현
Result result = new Result(); //result 객체생성
if(c == '+'){
result.setResult(a+b);
System.out.println("The result is " + result.getResult());
}
else if(c == '-'){
result.setResult(a-b);
System.out.println("The result is " + result.getResult());
}
else if(c == '*'){
result.setResult(a*b);
System.out.println("The result is " + result.getResult());
}
else if(c == '%'){
if(b == 0){ //0으로 나누는 경우 오류처리
System.out.println("Can't div with 0");
return;
}
result.setResult(a%b);
System.out.println("The result is " + result.getResult());
}
else if(c == '/'){
if(b == 0){ //0으로 나누는 경우 오류처리
System.out.println("Can't div with 0");
return;
}
result.setResult(a/b);
System.out.println("The result is " + result.getResult());
}
else{ //부호입력을 잘못했을경우 오류처리
System.out.println("plz type symbols (+, -, %, *, /)");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner 객체 생성
while(true) { //원할때까지 계산 반복
System.out.print("Type first Number ");
int firstNum = sc.nextInt();
System.out.print("Type calculator symbols ");
char symbols = sc.next().charAt(0);
System.out.print("Type second Number ");
int secondNum = sc.nextInt();
cal(firstNum, symbols, secondNum); //계산함수
System.out.println("Do you want cal again? type num '1'");
int keepCal = sc.nextInt();
if(keepCal != 1) break;
}
}
}
//getter, setter을 사용하지 않은 매서드
// public static int cal(int a, char c, int b){
// int result = 0;
// if(c == '+'){
// result = a + b;
// return result;
// }
// else if(c == '-'){
// result = a - b;
// return result;
// }
// else if(c == '*'){
// result = a * b;
// return result;
// }
// else if(c == '%'){
// if(b == 0){
// System.out.println("Can't div with 0");
// return 0;
// }
// result = a % b;
// return result;
// }
// else if(c == '/'){
// if(b == 0){
// System.out.println("Can't div with 0");
// return 0;
// }
// result = a / b;
// return result;
// }
// else{
// System.out.println("plz type symbols (+, -, %, *, /)");
// return 0;
// }
//
// }
AI없이 개발하시다니 대단하시네요
향후 괄호도 추가 하실런지 궁금합니다