JAVA/Study

[0201] 5. 제어문 (if,for,forfor), static 멤버 변수

1. 제어문

1.1 조건문 : if문, switch문

    - switch-case문 : 주로 조건이 하나의 변수 값이나 상수 값으로 구분되는 경우 사용된다.

    - if문 : 조건에 정해지지 않은 다양한 값을 검사해야할 때 사용, ex) 10 < age < 20;

    - switch문은 정수형으로 비교가 가능하며 JDK 7 이후부터 문자열도 비교가 가능하다.

    - switch문은 조건의 그룹화가 가능하다. 

    case 1:
    case 2:    // 1, 2, 3 중에 하나라도 조건을 만족하면 아래 수행문을 수행하게 된다.
    case 3:
              수행문;
              break;

1.2 반복문 : for문, while문, do-while문

    - for문은 값을 증가하거나 감소시키며 반복이 필요할 때 주로 사용된다. for (초기화식; 조건식; 증감식)

    - for문을 구성하는 요소는 코드가 중복되거나 논리 흐름상 사용할 필요가 없을 때 생략 가능.

    - while문은 조건식이 참인 동안 수행문 반복이 필요할 때 사용. while (조건식)

    - do-while문은 무조건 한번은 수행한 이후 조건식 검사가 필요할 때 사용.

    - 무한 반복 : 서비스가 멈추지 않고 끊임없이 돌아가야 할 경우, while(true), for(;;)

    - continue문 : 반복문과 함께 쓰이며 continue 아래의 수행문은 수행하지 않습니다.

    - break문은 조건문과 반복문을 종료 or 탈출(중괄호 기준) 할때 사용한다.

1.3 Label

    - Label은 반복문이 중첩되어 있을 때 바깥쪽 반복문으로 탈출이 필요한 경우 이름(라벨)을 붙여서 사용.

Label : for ( ; ; ) {
                      for ( ; ; ) {
                                  if (조건식)
                                         break Label;
                      }
          }  // label 이 붙여진 반복문 바깥으로 탈출한다.

2. static 멤버 변수

2.1 static 변수

    - 프로그램 실행시 메모리에 딱 한 번 공간이 할당되며 그 값은 모든 객체(인스턴스)가 공유합니다.

    - [static] [자료형] [변수 이름] : 이와 같은 형태로 선언되며 클래스명.변수명 으로 사용이 가능합니다.

    - 다른 용어로 '정적 변수', '클래스 변수' 라고도 불리웁니다.


소스 코드

package ex1;

import java.util.Scanner;

// 사용자로부터 입력 받는 정수값 1,3이 아닌 경우
// false로 돌려 받아서 유효성을 체크하는 프로그램을 구현하자.
public class Ex1_LimitCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("숫자를 입력하세요 : ");
        int number = Integer.parseInt(sc.nextLine());
        boolean chk = checkVal(number);
        System.out.println("check Number : " + chk);
    }
    // 인자값이 정수값 1, 3
    // 리턴값 boolean
    public static boolean checkVal(int num){ 
    // 1, 3 => true 그 외에는 false 를 반환
        if (num == 1 || num == 3) {
            return true;
        } else {
            return false;
        }
    }
}

package ex1;

public class Ex2_For {
    public static void main(String[] args) {
//        for1();
        int brnum = 5;
        for2(brnum);
    }

    private static void for1() {
        for (int i=0; i<10; i++)      // \t tab
            System.out.print("i : " + i + ",\t");   // for문의 실행영역
        System.out.println("");                     // for문의 바깥영역
    }

    private static void for2(int brnum) {
        for (int i=0; i<10; i++) {
            System.out.println(i);
            // i의 값이 인자로 전달 된 brnum과 같으면
            // 해당 for문을 종료해라
            if( i == brnum) break;
        }
    }
    // 연습문제)
    // 입력 받은 수가 홀수면 홀수, 짝수면 짝수를 출력해주는
    // 메서드를 정의해서 호출한 결과를 이미지로 소스와 결과를 출력합니다.
}

package ex1;

public class Ex2_Switch {
    public static void main(String[] args) {
        mySwitchType2();
    }
    public static void mySwitch() {
        int num = 3;
        // 임의의 수 num의 값에 해당되는 case 구문만 실행된다.
        // break문의 해당 switch문을 종료시킨다.
        switch (num) {
            default:    // default를 먼저 사용할경우 break문을 써줘야한다.
                System.out.println(num + "메뉴는 없습니다.");
                System.out.println("영역");
                break;
            case 1:
                System.out.println("1은 입력처리 입니다.");
                break;
            case 2:
                System.out.println("2는 출력처리 입니다.");
                break;
        }
    }
    public static void mySwitchType() {
        String num = "2";
        //jdk 7이상부터 switch문에서 String 비교 가능
        switch (num) {
            case "1":
                System.out.println("1은 입력처리 입니다.");
                break;
            case "2":
                System.out.println("2는 출력처리 입니다.");
                break;
            default:
                System.out.println(num + "메뉴는 없습니다.");            
        }
    }
    // 시험문제 응용해서 나올 예정 ***** 기본 자료형 실습 형태와 함께 복습해 둘 것
    public static void mySwitchType2() {
        char num = '2';
        switch (num) {
            case '1':
                System.out.println("1은 입력처리 입니다.");
                break;
            case '2':
                System.out.println("2는 출력처리 입니다.");
                break;
            default:
                System.out.println(num + " 메뉴는 없습니다.");            
        }
    }
    public static void mySwitchType3() {
        // boolean num = true;
        // long num = 2L;
        // double num = 2.1;
        // 논리형, 실수형, long형은 case로 비교 할 수 없다.
        
        int num = 2;
        switch (num) {
            case 1:
                System.out.println("1은 입력처리 입니다.");
                break;
            case 2:
                System.out.println("2는 출력처리 입니다.");
                break;
            default:
                System.out.println(num + " 메뉴는 없습니다.");            
        }
    }  
}

package ex1;

import java.util.Scanner;

// <요구사항> 메뉴 만들기
// 1 - 입력, 2 - 출력, 3 - 종료
// in : 정수, 문자
// out : 입력, 출력, 종료(프로그램 종료)
public class Ex3_Menu {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // label 지정 -> 라밸: for, while
        ex: for (int i = 0; i != 3;) {
            System.out.print("숫자를 입력하세요 : ");
            i = Integer.parseInt(sc.nextLine());
            menu(i);    // 1, 2, 3
        }
        sc.close();
    }

    public static void menu(int number) {
        // switch 안에 
        switch (number) {
            case 1:
                System.out.println(number + " - 입력 처리입니다.");
                break;
            case 2:
                System.out.println(number + " - 출력 처리입니다.");
                break;
            case 3:
                System.out.println(number + " - 종료 처리입니다.");
                break;
            default:
                System.out.println(number + " - 메뉴에 없는 숫자입니다.");
        }
    }
}

package ex1;

import java.util.Scanner;

public class Ex3_Menu1 {
    public static int holNum = 0;
    static int jjanNum = 0;
    public static void main(String[] args) {
        // UI 
        Scanner sc = new Scanner(System.in);
        // 팁 : 홀, 짝을 입력한 수를 계산하기 위해서 선언, 0 초기화
//        int holNum = 0;
//        int jjanNum = 0;
        // for(초기식;조건식;증감식) -> 비워둔 형태 무한 루프
        // break label, fpr, blocking 메서드, switch문
        exout: for(int i=0;;i++){
            System.out.print("메뉴 1: 홀수, 2: 짝수, 3: 종료 => ");
            int menu = Integer.parseInt(sc.nextLine()); // blocking 메서드
            String msg = holjjak(menu); // 값이 증가한 후 멤버에 기억
            switch(menu) {
            case 1:
                System.out.println(msg);
//                holNum++;
                break;
            case 2:
                System.out.println(msg);
//               jjanNum++;
                break;
            case 3:
                System.out.println(menu + " - 종료 처리입니다.");
                System.out.println("홀 입력수 : " + holNum);
                System.out.println("짝 입력수 : " + jjanNum);
                break exout;
            default:
                System.out.println(menu + " - 메뉴에 없는 숫자입니다.");
            }
        }
//        System.out.println("");
        // heap에 str이 참조하는 String 클래스의 "test" 객체 생성
        String str = "test";
        // 메서드 호출 -> stack에서 메서드가 호출되어 쌓인다.
        int num = str.length();
        sc.close();
    }
    // 모델을 정의 -> in : 정수 , 모델 -> out : 홀수, 짝수
    public static String holjjak(int number) {
        String msg = "";
        if (number % 2 == 0) {
            msg = "짝수";
            jjanNum++;
        } else {
            msg = "홀수";
            holNum++;
        }
        return number + " 는 " + msg + "입니다.";
    }
}

package ex1;

import java.util.Scanner;

// 연습문제)
// 입력 받은 수까지 홀수면 홀수, 짝수면 짝수를 출력해주는
// 메서드를 정의해서 호출한 결과를 이미지로 소스와 결과를 출력합니다.
public class Exam1_Quiz {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("숫자를 입력하세요 : ");
        int number = Integer.parseInt(sc.nextLine());
        oddCheck(number);
        sc.close();
    }
    public static void oddCheck(int number) {
        for (int i = 0; i <= number; i++) {
            if ((i % 2) == 1) {
                System.out.println("숫자 : " + i + " 홀수입니다.");
            } else {
                System.out.println("숫자 : " + i + " 짝수입니다.");
            }
        }

    }
}

package ex1;

import java.util.Scanner;

public class Exam2_Quiz {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("반복 숫자를 입력하세요 : ");
        int forNumber = Integer.parseInt(sc.nextLine());
        System.out.print("영역 숫자를 입력하세요 : ");
        int areaNumber = Integer.parseInt(sc.nextLine());

        loofnumber(forNumber, areaNumber);  // 입력 된 값을 메서드에 전달합니다.
        sc.close();
    }

    public static void loofnumber(int forNumber, int areaNumber) {
        for (int i = 1; i <= forNumber; i++) {  // 입력 된 반복 숫자만큼 실행
            if ((i % areaNumber) == 0) {        // 영역 값을 나눠서 나머지가 0이면
                System.out.println(i);          // 현재 값을 출력하며 다음 라인으로 넘겨줍니다.
            } else {                            // 나눈 값의 나머지가 0이 아닐 때
                System.out.print(i + "\t");     // 현재 값을 출력하며 \t으로 숫자 사이를 띄워줍니다.
            }
        }
    }
}

package ex2;

import java.util.Scanner;

public class Ex1_Game1 {
    static int totalGame = 0;
    public static void main(String[] args) {
        // 콘솔 입력 UI
        Scanner sc = new Scanner(System.in);
        int randomNum = 0;
        int inputNum = 0;
        for(;;) { 
            randomNum = (int) (Math.random() * 10) + 1; // CPU 랜던값 받아오기
            if (totalGame >= 5)         // 총 게임수가 5게임이 넘어갈 경우
                gameHint(randomNum);    // gameHint 메서드를 통해 업다운 힌트 제공
            System.out.print("1 ~ 10까지 숫자를 맞추세요 : ");
            inputNum = Integer.parseInt(sc.nextLine());
            boolean checkNum = randomNumberGame(inputNum, randomNum);
            if (checkNum == true){  // randomNumberGame 메서드를 통해 값을 확인
                break;              // 정답을 맞추면 true값을 넘겨받아 반복문 탈출
            }
        }
        sc.close();
    }
    public static boolean randomNumberGame(int inputNum, int randomNum) {
        totalGame++;                    // 게임 횟수 카운트
        if (inputNum == randomNum) {    // CPU 값과 인풋값 비교하여 맞췄을 경우
            System.out.println("CPU 값: " + randomNum + " 오^^ 정답입니다!");
            System.out.println("프로그램이 종료됩니다!!");
            return true;
        } else {                        // CPU 값과 인풋값이 다를 경우
            System.out.println("CPU 값: " + randomNum + " 아쉽습니다. 계속 해주세요!");
            System.out.println("5게임 이상 실패시 힌트를 드립니다! 현재 게임수 : " + totalGame);
            return false;
        }
    }
    // 5게임 이상 진행시에 힌트를 제공하는 메서드
    public static void gameHint(int randomNum) {
        System.out.println("===========================================");
        if (randomNum > 5) {
            System.out.print("hint : CPU 값은 5보다 큽니다");
        } else {
            System.out.println("hint : CPU 값은 5와 같거나 작습니다");
        }            
    }
}

package ex2;

import java.util.Scanner;

public class Ex2_Game2 {
    static int totalGame = 0;   // 총 게임횟수를 저장하는 전역변수
    static int countWin = 0;    // 승리 횟수를 저장하는 전역변수
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double winGameNum  = 0; // 승률 값을 넘겨받는 main 메서드의 지역변수
        int inputNum = 0;       // 게임 유저가 입력한 값을 저장하는 지역변수
        
        exitgame: for(;;) {     // for문 무한루프 실행
            System.out.print("1:홀, 2:짝, 3:종료, 숫자를 입력하세요 : ");
            inputNum = Integer.parseInt(sc.nextLine());
            
            switch (inputNum){  // 입력 된 값이 1,2 이면 게임 실행, 3이면 종료.
                case 1:
                case 2:
                    System.out.println("No : " + (totalGame+1));
                    oddAndEvenGame(inputNum);
                    winGameNum = gameWinner();
                    System.out.println("게임 승률 : " + (int)winGameNum + "%");
                    System.out.println("일정 승률을 5게임 이상 유지하면 경품 지급!!");
                    if (totalGame >= 5)
                        gift(winGameNum);
                    break;
                case 3:
                    System.out.println("홀짝 게임을 종료합니다.");
                    break exitgame;
                default:
                    System.out.println("잘못 된 숫자 입력입니다.");
            }   // switch문 종료
            System.out.println("=============================================");
        }       // for문 종료
        sc.close();
    }
    // 유저가 입력한 값을 전달받아 CPU 값과 홀,짝 구분하여 출력.
    public static void oddAndEvenGame(int inputNum) {
        totalGame++;    // 게임 횟수 증가
        int randomNum = (int) (Math.random() * 2) + 1; // CPU 랜덤값 받아오기
        if (randomNum % 2 == 0) {
            System.out.println("CPU : 짝");
        } else {
            System.out.println("CPU : 홀");
        }
        
        if (inputNum % 2 == 0) {
            System.out.println("YOU : 짝");
        } else {
            System.out.println("YOU : 홀");
        }
        
        if (randomNum == inputNum) {    // CPU 값과 입력 값이 같을때 승리로 카운트
            System.out.println("WIN : 당신이 이겼습니다!!");
            countWin++; // 승리 횟수 증가
        } else {
            System.out.println("LOSE : 당신은 졌습니다! ㅠ_ㅠ");
        }
    }
    // 승률을 계산하여 반환해주는 메서드
    public static double gameWinner() {
        double winGameNum = ((double)countWin / (double)totalGame) * 100 ;
        return winGameNum;
    }
    // 승률 값을 전달받아 경품을 차등 지급해주는 메서드
    public static void gift(double giftNum) {
        if (giftNum == 100) {
                System.out.println("축하합니다! 100프로 승률로 TV를 선물로 드립니다!");
        } else if (giftNum < 100 && giftNum >= 80) {
                System.out.println("축하합니다! A등급 달성! 모니터를 선물로 드립니다!");
        } else if (giftNum < 80 && giftNum >= 60) {
                System.out.println("축하합니다! B등급 달성! 키보드를 선물로 드립니다!");
        } else {
                System.out.println("아쉽지만 승률이 낮아 선물 증정이 어렵습니다");
        }
        System.out.println("-- 게임 횟수와 승률은 초기화됩니다. --");
        totalGame = 0; countWin = 0;
    }
}

package ex2;

public class Ex2_MySwitch {
    // 요구 사항
    // input -> 모델을 만들고 -> output
    // 사과 -> 빨간색
    // 배 -> 노란색
    // 키위 -> 녹색

    // step1) 메인 메서드를 정의
    public static void main(String[] args) {
        // step4) 일단 호출해보자.
        String fname = "키위";
        foodColor(fname);
    }
    // step2) 메서드를 정의.
    // 요구 사항에 따른 변수를 생각
    // input에 해당 되는 변수 : 문자열
    // output에 해당 되는 변수 : 문자열 출력
    public static void foodColor(String fname) {
        // step3) 전달받은 변수값 출력형태의 견본을 만들어 봅니다.
        // step5) 제어문을 결정하고 실행.
 /*       switch (fname) {
            case "사과":
                System.out.println(fname + "은(는) 빨간색입니다.");
                break;
            case "배":
                System.out.println(fname + "은(는) 노란색입니다.");
                break;
            case "키위":
                System.out.println(fname + "은(는) 녹색입니다.");
                break;
            default:
                System.out.println(fname + "은(는) 알 수 없습니다.");
        }*/
        String res = "";
        // 만약에 300개 작업에 대한 효율성?
        if (fname.equals("사과")) {
            res = "빨간색";
        } else if (fname.equals("배")) {
            res = "노란색";
        } else if (fname.equals("키위")) {
            res = "녹색";
        }
        System.out.println(fname + "는(은) " + res + "입니다.");
    }
}