JAVA / / 2019. 6. 12. 17:08

[Java] 계산기 만들기 (switch문 연습)

반응형
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Scanner
 
public class Calculator {
    public static void main(String[] args) {
        Scanner sc;
        sc = new Scanner(System.in);
        float num1;    //실수형
        float num2;
        String oper; //문자열
        String con;
        boolean a; //논리값
        
        do{
            System.out.print("숫자 입력 : ");
            num1 = sc.nextFloat();
            a = true;
            do {
                System.out.print("연산자 입력 : ");
                oper = sc.next();
                
                switch(oper) {
                    case "+":
                        a=false;
                        break;
                    case "-":
                        a=false;
                        break;
                    case "*":
                        a=false;
                        break;
                    case "/":
                        a=false;
                        break;
                    default:
                        System.out.print("연산자를 다시 입력해주세요 \n ");                
                    }                
                }while(a);
                
            System.out.print("숫자 입력 : ");
            num2 = sc.nextFloat();
            
            switch(oper) {
            case "+":
                System.out.println(num1+num2);
                break;
            case "-":
                System.out.println(num1-num2);
                break;
            case "*":
                System.out.println(num1*num2);
                break;
            case "/":
                System.out.println(num1/num2);
                break;
            default:
                System.out.print("처음부터 다시 입력해주세요 \n ");
                continue;              
            }
        
            System.out.print("계산을 계속 하시려면  y 혹은 Y를 입력해 주세요 : ");
            con = sc.next();
            if(con.equals("y"|| con.equals("Y") ){
                continue;
                }
                else{
                    System.out.println("종료합니다.");
                    break;
                }    
            }while(true);
    }
 
 
 
}
cs

계산기를 실행 시킨 화면. 잘못된 연산자 입력시 다시 실행

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유