[java] 계산기 만들기

심심이·2024년 1월 21일
0

java

목록 보기
10/46
public class Calcurator {

    void calculator(int number1, int number2, String str) {
        double total = 0;
        
        if("+".equals(str)) {
            total = number1 * number2;
            System.out.println(number1 + str + number2 + "=" + (int)total);
        } 
        
        else if ("-".equals(str)){
            total = number1 - number2;
            System.out.println(number1 + str + number2 + "=" + (int)total);
        } 
        
        else if ("*".equals(str)){
            total = number1 * number2;
            System.out.println(number1 + str + number2 + "=" + (int)total);
        } 
        
        else if ("/".equals(str)){
        
            total = number1 / number2;
            if (total == 0) {
                System.out.println(number1 + str + number2 + "=" + (int)total);
            } else {
                System.out.println(number1 + str + number2 + "=" + total);
            }
            
        } else {
            System.out.println("사칙연산을 다시 선택하세요.");
		}
    }
}
import java.util.Scanner;

public class CalcuratorMain {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        Calcurator cal = new Calcurator();
        String str = "";
        try {
            System.out.println("첫번째 정수 입력");
            str = sc.nextLine();
            int num1 = Integer.parseInt(str);

            System.out.println("두번째 정수 입력");
            str = sc.nextLine();
            int num2 = Integer.parseInt(str);

            System.out.print("사칙연산을 선택하세요(+ - * /) =>");
            str = sc.nextLine();

            cal.calculator(num1,num2,str);
        } catch (NumberFormatException e) {
            System.out.println(str + "는 올바른 데이터가 아닙니다. 정확한 값을 입력해주세요.");
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌 수 없습니다.");
        }

    }
}
profile
개발하는 심심이

0개의 댓글

관련 채용 정보