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
package quiz1;
 
import java.util.Scanner;
 
//문자열 입력 받아서 대 <---> 소문자 출력하는 프로그램 
public class Ex01_API {
 
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        
        char[] input = null;
        
        System.out.print("input String => ");
        String str = sc.next();
        input = str.toCharArray();
        
        for (int i=0; i<str.length(); i++) {
            
            if( (65 <= (int)input[i]) && ((int)input[i] <= 90)) {
                input[i] = str.toLowerCase().charAt(i);
                
            } else if ((97 <= (int)input[i]) && ((int)input[i] <= 122)){
                input[i] = str.toUpperCase().charAt(i);
 
            } else { 
                input[i] = str.charAt(i);
            }// if end
        } //for end 
 
        System.out.print("output String =>");
        
        for(int i=0; i<input.length; i++) {
        System.out.print(input[i]);
        }
    }
 
}
 
cs

<BMI.java>

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package quiz3.ex01.io;
 
 
//몸무게, 키 입력받아서 BMI 계산하기
public class Bmi2 {
 
    double weight = 0;
    double height = 0;
    double bmi = 0;
    String bmi_result = null;
    int num=0;
 
    // 생성자
    public Bmi2() {
 
    }
    
    public Bmi2(double weight, double height, int num) {
        this.num = num;
        this.weight = weight;
        this.height = height;
        bmiCalc(weight, height);
    }
    
 
    // getter, setter method
    public double getWeight() {
        return weight;
    }
 
    public void setWeight(double weight) {
        this.weight = weight;
    }
 
    public double getHeight() {
        return height;
    }
 
    public void setHeight(double height) {
        this.height = height;
    }
 
    public double getBmi() {
        return bmi;
    }
 
    public void setBmi(double bmi) {
        this.bmi = bmi;
    }
    
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
    
    
    //계산 처리
    public void bmiCalc(double w, double h) {
        bmi = w / ( (h/100.0* (h/100.0) ) ;        
        bmiResult(bmi);
    }
    
    public void bmiResult(double bmi) {
        
        if(bmi < 18.5) {
            bmi_result = "체중부족";
        } else if(bmi >= 18.5 && bmi <= 22.9) {
            bmi_result = "정상";
        } else if(bmi >= 23.0 && bmi <= 24.9) {
            bmi_result = "과체중";
        } else {
            bmi_result = "비만";
        }
    }
    
    //출력 method
    public void display() {
        System.out.println("<<<<<" + num + "번째 정보>>>>>");
        System.out.println("▶몸무게: " + weight + "kg");
        System.out.println("▶키: " + height + "cm");
        System.out.printf("▶BMI: %.2f \n", bmi);
        System.out.println("▶판정: " + bmi_result);
    }
 
 
}
 
cs

<Main.java>

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package quiz3.ex01.io;
 
import java.io.*;
import java.util.*;
 
public class Main2 {
 
    public static void main(String[] args) {
 
        Bmi2 b = new Bmi2();
 
        // ArrayList 생성
        ArrayList<Bmi2> list = new ArrayList<Bmi2>();
 
        int count = 0;
        int num = 0;
 
        // readLine()을 쓰기위해 BufferedReader 선언
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        // 파일 저장
        ObjectOutputStream bos = null;
        File f = new File("bmi결과.txt"); //저장할 파일(상대주소 - 현재 폴더에 저장됨)
 
        try {
            FileOutputStream fos = new FileOutputStream(f, true); // append mode -> 뒤에 차례로 계속 추가
            bos = new ObjectOutputStream(fos);
 
            System.out.println("-----------------BMI계산 프로그램-------------------");
            
            while (true)
                block: {
                    System.out.println("***원하는 메뉴를 입력해주세요***(1.추가, 2.삭제, 3.출력, 4.종료)");
                    num = Integer.parseInt(br.readLine());
 
                    switch (num) {
                    case 1// 추가
                        count++;
 
                        System.out.print("키>> ");
                        double h = Double.parseDouble(br.readLine());
 
                        System.out.print("몸무게>> ");
                        double w = Double.parseDouble(br.readLine());
 
                        list.add(new Bmi2(w, h, count)); // list에 추가*****??->객체로 넣으면 그곳에있는 모든 값들이 list에 저장됨
 
                        bos.writeObject(b.weight); // 파일에 저장하기
                        bos.writeObject(b.weight);
                        bos.writeObject(b.bmi);
                        bos.writeObject(b.bmi_result);
                        System.out.println("bmi결과1.txt 저장 완료.");
                        break;
                        
                    case 2// 삭제 - 삭제부분 입력값과 list안의 값 비교 코드 추가
                        if (list.isEmpty()) { // list안에 요소가 없다면
                            System.out.println("삭제할  정보가 없습니다.");
                            continue// ->continue, break둘다 가능 
                        }
 
                        while (true) {
                            System.out.print("삭제하기를 원하는 정보의 번호를 입력하시오 ( 1 ~ ) : ");
                            int remove_num = Integer.parseInt(br.readLine()); // 삭제할 번호입력받음
 
                            for (int i = 0; i < list.size(); i++) { // list안의 모든 정보와 비교
 
                                if (remove_num == list.get(i).getNum()) {
                                    list.remove(i); //리스트에서 삭제 
                                    System.out.println("삭제되었습니다.");
                                    break block; //삭제한 후, 메뉴 선택 구문으로 돌아감 
                                }
                                continue// i번째 번호와 같지 않으면, i+1번째번호와 다시 비교
                            } // for end
 
                            // list안의 모든 정보와 비교한후에도 같은 정보가 없다면
                            System.out.println("일치하는 정보가 없습니다.");
                        } // while end
                        
                    case 3// 출력
                        if (list.isEmpty()) { // list안에 요소가 없다면
                            System.out.println("조회할 정보가 없습니다.");
                            continue
                        }
 
                        System.out.println("***전체 목록***");
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).display();
                            System.out.println();
                        }
                        break;
                        
                    case 4// 종료
                        System.out.println("종료되었습니다.");
                        System.exit(0);
                        
                    default:
                        System.out.println("다시 입력해주세요.");
                    } // switch end
                } // while end
 
        } catch (
 
        Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
}
 
cs

고민했던 코드 

<Heart.java>

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
package quiz1.thread;
 
public class Heart implements Runnable {
 
    @Override
    public void run() {
 
        try {
            while (true) {
                int i;
                System.out.println();
 
                for (i = 4; i < 10; i += 2) {
                    MakeHeart1(10 - i);
                    MakeHeart2(i * 2);
                    MakeHeart1((10 - i) * 2);
                    MakeHeart2(i * 2);
                    System.out.println();
                }
 
                for (i = 20; i >= 0; i -= 2) {
                    MakeHeart1(20 - i);
                    MakeHeart2(i * 2);
                    System.out.println();
                }
 
                Thread.sleep(500);
                
                for (i = 4; i < 10; i += 2) {
                    MakeHeart1(10 - i);
                    MakeHeart3(i * 2);
                    MakeHeart1((10 - i) * 2);
                    MakeHeart3(i * 2);
                    System.out.println();
                }
 
                for (i = 20; i >= 0; i -= 2) {
                    MakeHeart1(20 - i);
                    MakeHeart3(i * 2);
                    System.out.println();
                }
 
                Thread.sleep(500);
 
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
    }
 
    public void MakeHeart1(int a) {
        int j;
        for (j = 0; j < a; j++) {
            System.out.print(" ");
        }
    }
 
    public void MakeHeart2(int a) {
        int j;
        for (j = 0; j <= a; j++) {
            System.out.print("♡");
        }
    }
 
    public void MakeHeart3(int a) {
        int j;
        for (j = 0; j <= a; j++) {
            System.out.print("♥");
        }
    }
 
}
 
cs

<HeartMain.java>

1
2
3
4
5
6
7
8
9
10
11
package quiz1.thread;
 
public class HeartMain {
 
    public static void main(String[] args) {
        
        new Thread(new Heart()).start();
 
    }
}
 
cs

<Score.java>

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package quiz2.ex01.score;
 
//수정하기를 구체적으로 나누기 
public class Score_2 {
 
    protected String name;
    protected int kor, eng, com, tot;
    protected double avg;
    protected char grade;
 
    // 생성자
    public Score_2() {
 
    }
 
    public Score_2(String name, int kor, int eng, int com, int tot, double avg, char grade) {
        super();
        this.name = name;
        this.kor = kor;
        this.eng = eng;
        this.com = com;
        this.tot = tot;
        this.avg = avg;
        this.grade = grade;
    }
    
    public Score_2(String name, int kor, int eng, int com) {
        this.name = name;
        this.kor = kor;
        this.eng = eng;
        this.com = com;
    }
 
    
    
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getKor() {
        return kor;
    }
 
    public void setKor(int kor) {
        this.kor = kor;
    }
 
    public int getEng() {
        return eng;
    }
 
    public void setEng(int eng) {
        this.eng = eng;
    }
 
    public int getCom() {
        return com;
    }
 
    public void setCom(int com) {
        this.com = com;
    }
 
    public int getTot() {
        return tot;
    }
 
    public void setTot(int tot) {
        this.tot = tot;
    }
 
    public double getAvg() {
        return avg;
    }
 
    public void setAvg(double avg) {
        this.avg = avg;
    }
 
    public char getGrade() {
        return grade;
    }
 
    public void setGrade(char grade) {
        this.grade = grade;
    }
 
    // output method
    public void display(int num) {
 
        System.out.println("\n\n****** " + (num + 1+ "번학생 " + name + " 님의 성적표 ******");
        System.out.println("Kor : " + kor + "\tEng : " + eng + "\tCom : " + com);
        System.out.print("Total : " + tot);
        System.out.printf("\tAverage : %.2f\tGrade : %c", avg, grade);
    }
 
}
 
cs

 


<ScoreManager.java>

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
package quiz2.ex01.score;
 
import java.util.ArrayList;
 
public class ScoreManager_2 extends Score_2{
    
    ArrayList<Score_2> list = new ArrayList<Score_2>();
 
    public ScoreManager_2() {
        
    }
 
    public ScoreManager_2(String name, int kor, int eng, int com, int tot, double avg, char grade) {
        Score_2 s = new Score_2(name, kor, eng, com, tot, avg, grade);
        list.add(s);
    }
    
    //추가
    public void ScoreAdd(String name, int kor, int eng, int com, int tot, double avg, char grade) {
        Score_2 s = new Score_2(name, kor, eng, com, tot, avg, grade);
        list.add(s);
    }
    
    //삭제
    public void ScoreRmv(int i) {
        System.out.println("\n\n* 삭제된 학생");
        list.get(i-1).display(i);
        System.out.println("--------------");
        list.remove(i-1);
    }
    
    //수정->각각 수정하려면 필요없..음(main에서 실행가능)
//    public void ScoreCh(int i, String name, int kor, int eng, int com) {
//        Score_2 s = new Score_2(name, kor, eng, com);
//        list.set(i-1, s);
//    }
    
 
    
    //출력
    public void display(){
        System.out.println("저장된 학생 수 : " + list.size());
        for(int i=0; i<list.size(); i++){
            System.out.println();
            list.get(i).display(i);
        }// for
    }// display()
    
}// ScoreManaget_2 end
 
cs

<Main.java>

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package quiz2.ex01.score;
 
//수정하기를 구체적으로 나누기 
import java.util.Scanner;
 
public class MainEntry_2 {
    static String name;
    static int kor;
    static int eng;
    static int com;
    static int tot;
    static double avg;
    static char grade;
 
    public static void main(String[] args) {
        ScoreManager_2 sm = new ScoreManager_2();
 
        Scanner sc = new Scanner(System.in);
        int edit_num;
 
        try {
            while (true) {
                System.out.println("\n\n*-*-*-*-* 메뉴 *-*-*-*-*");
                System.out.println("1. 학생 정보 입력");
                System.out.println("2. 학생 정보 삭제");
                System.out.println("3. 학생 정보 수정");
                System.out.println("4. 모든 학생 보기");
                System.out.println("5. 종료");
                System.out.println("----------------------");
                System.out.print(" >> ");
                int inNum = sc.nextInt();
 
                try {
                    switch (inNum) {
                    case 1:
                        System.out.println("\n*-*-*-* 1. 학생 정보 입력 *-*-*-*");
                        inScore();
                        sm.ScoreAdd(name, kor, eng, com, tot, avg, grade);
                        System.out.println("* 입력완료");
                        break;
                    case 2:
                        if(sm.list.isEmpty()) {
                            System.out.println("삭제할 학생이 없습니다.");
                            continue;
                        }
                        System.out.println("\n*-*-*-* 2. 학생 정보 삭제 *-*-*-*");
                        sm.display();
                        System.out.println("---------------------------");
                        System.out.print("삭제할 학생의 번호를 입력하세요 >> ");
                        inNum = sc.nextInt();
                        sm.ScoreRmv(inNum);
                        System.out.print("삭제되었습니다.");
                        break;
                    case 3:
                        if(sm.list.isEmpty()) {
                            System.out.println("수정할 학생이 없습니다.");
                            continue;
                        }
                        System.out.println("\n*-*-*-* 3. 학생 정보 수정 *-*-*-*");
                        sm.display();
                        System.out.println("---------------------------");
                        System.out.print("수정할 학생의 번호를 입력하세요 >> ");
                        inNum = sc.nextInt();
 
//                        do { //=>1)do ~ while 이용
                        while (true) { //=>2)while 이용
                            System.out.println("수정할 학생의 정보를 입력하세요.(1.이름, 2.국어점수, 3.영어점수, 4.전산점수)");
                            edit_num = sc.nextInt();
                            switch (edit_num) {
                            case 1// 이름수정
//                                editName();
                                System.out.println("수정할 이름을 입력해주세요=>");
                                sm.list.get(inNum - 1).setName(sc.next());
                                System.out.println("수정되었습니다.");
//                                sm.ScoreCh(inNum, name, kor, eng, com); 
                                break;
                            case 2// 국어점수 수정
                                System.out.println("국어점수를 입력해주세요=>");
                                sm.list.get(inNum - 1).setKor(sc.nextInt());
                                System.out.println("수정되었습니다.");
                                break;
                            case 3// 영어점수 수정
                                System.out.println("영어점수를 입력해주세요=>");
                                sm.list.get(inNum - 1).setEng(sc.nextInt());
                                System.out.println("수정되었습니다.");
                                break;
                            case 4// 전산점수 수정
                                System.out.println("전산점수를 입력해주세요=>");
                                sm.list.get(inNum - 1).setEng(sc.nextInt());
                                System.out.println("수정되었습니다.");
                                break;
                            default:
                                System.out.println("수정할 정보의 번호를 다시 입력해주세요.");
                                continue;
                            } // in switch end
 
                            System.out.println("계속 수정하시겠습니까?");
                            String con = sc.next();
                            if (con.equalsIgnoreCase("n")) {
                                break;
                            }
                        } //in while end
//                        } while (edit_num != 1 && edit_num != 2 && edit_num != 3 && edit_num != 4); // do while end
                        break;
                    case 4:
                        if(sm.list.isEmpty()) {
                            System.out.println("저장된 학생정보가 없습니다.");
                            continue;
                        }
                        System.out.println("\n*-*-*-* 4. 모든 학생 보기 *-*-*-*");
                        sm.display();
                        break;
                    case 5:
                        System.out.println("\n* 프로그램을 종료합니다.");
                        System.exit(0);
                        break;
                    default:
                        System.out.println("\nerr)잘못입력하셨습니다. 다시 입력해주세요.");
                    } // out switch end
                } catch (Exception e) {
                    System.out.println("err) 없는 학생입니다. 다시 입력해주세요.");
                } // try catch
            } // out while end
        } catch (Exception e) {
            System.out.println("err) 잘못 입력하셨습니다. 프로그램을 종료합니다.");
        } // try catch
 
    }
 
    public static void inScore() {
        Scanner sc = new Scanner(System.in);
 
        System.out.print("학생 이름을 입력해주세요: ");
        name = sc.next();
 
        do {
            System.out.println("학생의 국어점수를 입력하세요(0~100점사이값만 넣으세요) : ");
            kor = sc.nextInt();
        } while ((kor < 0|| (kor > 100));
 
        do {
            System.out.println("학생의 영어점수를 입력하세요(0~100점사이값만 넣으세요) : ");
            eng = sc.nextInt();
        } while ((eng < 0|| (eng > 100));
 
        do {
            System.out.println("학생의 전산점수를 입력하세요(0~100점사이값만 넣으세요) : ");
            com = sc.nextInt();
        } while ((com < 0|| (com > 100));
 
        process(name, kor, eng, com);
    }
 
    // 계산처리
    public static void process(String name, int kor, int eng, int com) {
 
        tot = kor + eng + com;
        avg = tot / 3.0;
 
        grade(avg);
    } // process end
 
    public static void grade(double avg) {
 
        if (avg <= 100 && avg > 90) {
            grade = 'A';
        } else if (avg <= 90 && avg > 80) {
            grade = 'B';
        } else if (avg <= 80 && avg > 70) {
            grade = 'C';
        } else if (avg <= 70 && avg > 60) {
            grade = 'D';
        } else
            grade = 'F';
    } // grade end
 
}
 
cs

 

try ~ catch 문에서 catch는 여러개 쓸 수 있음

main메소드가 있는 클래스 안의 다른 메소드와 변수들은 접근지정자가 모두 main과 같은 static이여야만 함

 ->그래야 main메소드 안에서 불러오고 사용가능

while(true)와 do ~ while 모두 사용해봄 

 ->do ~ while은 while(조건)에서 조건에 맞는 상황에는 계속 실행: 여러 조건 넣을 때 ||와 && 혼동하지 않기

무한루프 안의 if문 안에서의 break; 무한루프 안의 switch문 안에서의 break;

while(true) {

     if문 ~~ {

        break; }} 
==>무한루프 탈출

while(true) {

     switch문~{

     case 1 : break; }}

==>switch문 탈출, while이 다시 반복 실행 

 

     

▶BufferedReader의 readLine()을 이용한 연산 프로그램 

docs.oracle.com/javase/8/docs/api/

 

Java Platform SE 8

 

docs.oracle.com


<잘못된 코드>

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
package quiz1.ex01.io;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
//숫자 2개, 연산자 1개 입력받아서 사칙연산 프로그램 작성(io - BufferedReader)
public class MainEntry {
 
    public static void main(String[] args) throws IOException {
 
        String op = null;
        int su1 = 0, su2 = 0;
        double result = 0.;
 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
 
            while (true)
                second: {
                    System.out.println("숫자1을 입력하세요");
                    su1 = Integer.parseInt(br.readLine());
 
                    System.out.println("숫자2를 입력하세요.");
                    su2 = Integer.parseInt(br.readLine());
 
                    System.out.println("숫자1과 숫자2의 연산에 사용할 연산자를 고르세요.(+, -, *, /)");
                    op = br.readLine();
                    
                    switch (op) {
                    case "+":
                        result = su1 + su2;
                        break second;
                    case "-":
                        if (su1 >= su2) {
                            result = su1 - su2;
                        } else {
                            result = su2 - su1;
                        }
                        break second;
                    case "*":
                        result = su1 * su2;
                        break second;
                    case "/":
                        if (su1 >= su2) {
                            result = su1 / su2;
                        } else {
                            result = su2 / su1;
                        }
                        break second;
                    default
                        System.out.println("+,-,*,/ 중에 입력해주세요.");
                        continue;
                    
                    } // switch end
 
                } // while end
        } catch (Exception e) {
            e.printStackTrace();
        }
//==================!무한루프에서 빠져나오지 못함!==================ㅜㅜ
        if (su1 >= su2) {
            System.out.printf("%d %s %d = %.2f", su1, op, su2, result);
 
        } else {
            System.out.printf("%d %s %d = %.2f", su2, op, su1, result);
        }
    }// main end
}
 
cs

-while(true)의 무한루프를 빠져나오지 못한다.

-while(true) second: { -> 식별자를 넣어

  break second;를 해도 while을 빠져나가는게 아니라, 다시 while문을 시작한다.

-default: 

     continue; 와 break; 와 아무것도 작성하지 않아도 모두 while문으로 돌아가 시작된다.


<완성한 코드>

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
75
76
77
package quiz1.ex01.io;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
//숫자 2개, 연산자 1개 입력받아서 사칙연산 프로그램 작성(io - BufferedReader)
public class MainEntry2 {
    public static void main(String[] args) {
 
        String op = null;
        int su1 = 0, su2 = 0;
        double result = 0.;
 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        System.out.println("<<<<<operate program>>>>>");
        try {
            while (true) {
                System.out.println("숫자1을 입력하세요");
                su1 = Integer.parseInt(br.readLine());
 
                System.out.println("숫자2를 입력하세요.");
                su2 = Integer.parseInt(br.readLine());
 
                System.out.println("숫자1과 숫자2의 연산에 사용할 연산자를 고르세요.(+, -, *, /)");
                op = br.readLine();
 
                switch (op) {
                case "+":
                    result = su1 + su2;
                    break;
                case "-":
                    if (su1 >= su2) {
                        result = su1 - su2;
                    } else {
                        result = su2 - su1;
                    }
                    break;
                case "*":
                    result = su1 * su2;
                    break;
                case "/":
                    if (su1 >= su2) {
                        result = su1 / su2;
                    } else {
                        result = su2 / su1;
                    }
                    break;
                default:
                    System.out.println("연산자를 다시 입력해주세요");
                    continue;
                }// switch end
 
                if (su1 >= su2) {
                    System.out.printf("%d %s %d = %.2f", su1, op, su2, result);
 
                } else {
                    System.out.printf("%d %s %d = %.2f", su2, op, su1, result);
                }
 
                System.out.println("\n다시 입력하시겠습니까?");
                String re = br.readLine();
                if (re.equalsIgnoreCase("y")) {
                   continue; //==>안써도 다시 반복됨!!
                } else {
                    System.out.println("계산프로그램을 종료합니다.");
                    System.exit(0);
                }
                
            } // while end
        } catch (Exception e) {
            e.printStackTrace();
        } // try end
 
    }
 
}
 
cs

-switch문 다음에 이어질 코드(출력과 재실행 유무)들을 모두 while(true)에 넣음

-switch문 안에서 작성한 break;가 실행되면 while(true)가 아니라, switch를 빠져나오게 됨

-default: continue;가 실행되면, 다시 while문의 처음으로 올라가서 반복실행됨

 

Unreachable code 에러

  Unreachable code란? 도달하지 않는 구문, 절대 실행될 수 없는 구문 

  In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.[출처.위키백과]

en.wikipedia.org/wiki/Unreachable_code

 

Unreachable code - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the

en.wikipedia.org

 

+ Recent posts