기루 기룩 기록

자바예제 03 생성자 오버로딩 본문

JAVA

자바예제 03 생성자 오버로딩

남기루 2019. 6. 19. 09:16
반응형
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
package homeW;
 
import java.util.Scanner;
 
public class CalcClass {
private int num1,num2;
private String oper;
 
//생성자
CalcClass(){}
CalcClass(int n1, int n2){
    num1 = n1;
    num2 = n2;
}
CalcClass(String o){
    oper = o;
}
//set
public void setNum1(int n) {num1 = n;}
public void setNum2(int n) {num2 = n;}
public void setOper(String o) {oper = o;}
//get
public int getNum1() {return num1;}
public int getNum2() {return num2;}
public String getOper() {return oper;}
    
    public static void main(String[] args) {
        Scanner sc;
        sc = new Scanner(System.in);
        
        CalcClass cs = new CalcClass();
 
        String replay;
        do {
            System.out.print("첫번째 수: ");
            cs.setNum1(sc.nextInt());
            System.out.print("연산자 +, -, *, /: ");
            cs.setOper(sc.next());         //연산자 입력
            System.out.print("두번째 수: ");
            cs.setNum2(sc.nextInt());    //두번째 정수 입력
 
            switch(cs.getOper()) {         //연산자에 따라 case를 나눈다
            case "+"System.out.println(cs.getNum1()+cs.getNum2());
            break;
            case "-"System.out.println(cs.getNum1()-cs.getNum2());
            break;
            case "*"System.out.println(cs.getNum1()*cs.getNum2());
            break;
            case "/"System.out.println(cs.getNum1()/cs.getNum2());
            break;
            default:                      //다른 값이 들어올 경우
            System.out.println("잘못 입력했습니다.");
        }
            System.out.println("다시 하시겠습니까? (Y/N)");
            replay = sc.next();               //비교할 값을 입력받음
        }while(replay.equals("y")||replay.equals("Y"));         //replay가 "y"나 "Y"일 경우 do를 반복
    
        System.out.println("끝났습니다.");                         //"y"나 "Y" 가 아닌 값을 입력받았을 경우 종료
 
    }
 
}
 

 

반응형