JAVA/Study

[0129] 4. 연산자, 조건문(if else)

1. 연산자

1.1 연산자 종류 : 단항 > 이항 > 삼항 3가지이며 단항 연산자의 우선 순위가 제일 높다.

    - 대입 연산자 (=) : 이항 연산자 중 우선 순위가 가장 낮다.

    - 산술 연산자 (+, -, *, /, %) : 사칙 연산에서 사용하는 연산자

    - 증감 연산자 (++,--) : 연산자 앞이나 뒤에 사용. 값을 1만큼 늘리거나 뺀다.

     └ 연산자를 피연산자(ex:변수) 에 사용할 때와 에 붙여 사용할때 결과가 달라질 수 있다.

     └ val = ++num;    /    num 값이 1 증가후 val 변수에 대입된다.

     └ val = num++;    /    val에 num의 현재 값을 대입한 후 값을 1 증가시킨다.

    - 관계 연산자 (>, <, >=, <=, ==, !=) : 두 개의 항 값을 검사하여 truefalse 를 반환.

    - 논리 연산자 (&&, ||, !) :  두 명제의 결과 값을 검사하여 truefalse 를 반환.

    - 복합 대입 연산자 (+=, -=, *=... 외) : 대입 연산자와 다른 연산자를 조합해 하나의 연산자처럼 사용

    - 이 외에 부호 연산자, 조건 연산자, 비트 연산자 등이 있으며 상세한 내용은 아래 링크 참조.

    - http://www.devkuma.com/books/pages/11

2. 조건문 (if, else)

2.1 조건문 : 주어진 조건에 따라 다른 문장을 선택 할 수 있도록 프로그래밍 하는 것

    if (조건식) {

        수행문1;  // 조건식이 참(true)일 경우에 이 문장을 수행

    } else {

        수행문2;  // 조건식이 거짓(false)일 경우에 이 문장을 수행

    }

 

2.2 주의사항 : 중괄호와 들여쓰기 사용시 주의!

    - 수행문이 하나이든 두 개 이상이든 항상 중괄호로 표시해 주는 것이 좋다! (가독성, 오류 방지)

    - 중괄호 블록 내부의 문장은 들여쓰기를 하여 가독성을 높여주여야한다. (보기 좋은 코드)

 

Tip) 코딩을 시작할 때 머릿속에 생각한것을 바로 코드로 옮기는 것이 어렵다면...

  └ 구현하려고하는 내용의 순서도를 그려보거나 로직을 만들어 한글로 유사 코드를 만들어본다.

  └ 손코딩을 하다보면 구현하려는 프로그램에 필요한 변수와 흐름을 정리 할 수 있다.


소스 코드

package ex1;

import java.util.Scanner;

public class Ex1_MathRandom {
    public static void main(String[] args) {
        // java.lang.Math 클래스 안에서 난수를 발생하기 위해서 static random() 메서드를 호출
        Scanner sc = new Scanner(System.in);
        System.out.print("1 ~10까지의 숫자 중에서 하나를 입력하세요 : ");
        int input = Integer.parseInt(sc.nextLine());
        // 0 부터 ~9 난수를 발생하기 때문
        // +1 형태로 연산을 해서 값을 설정
        int comNum = (int) (Math.random() * 2) + 1;
        System.out.println("------------------------------------------");
        System.out.println("CPU의 값 : " + comNum + " / 입력한 값 : "
        + input + " / 결과 : " + (input == comNum));
    }
}

package ex1;

public class Ex2_Oper {

    public static void main(String[] args) {
        int a = 0;
        a += 10; // a = a + 10; 이순간 a값은 10이 된다.
        System.out.println(a);
        System.out.println("1) a -=5 : " + (a -= 5));
        System.out.println(a);
        System.out.println("2) a *=10 : " + (a *= 10));
        System.out.println(a);
        System.out.println("3) a /= 2 : " + (a /= 2));
        System.out.println(a);
        System.out.println("4) a %= 2 : " + (a %= 2));
        System.out.println(a);
    }
}

package ex1;

public class Ex3_Oper {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        boolean c = ((a+=12)>b) || (a==(b+=2)); // || 는 앞에 조건이 true일 경우 뒤 조건은 무시된다.
        System.out.println("c = " + c);
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("---------");
        
        a = 10;
        b = 20;
        boolean c2 = ((a+=12)>b) | (a==(b+=2)); // 비트 연산자는 두 조건을 다 실행한다.
        System.out.println("c2 = " + c);
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("---------");
    }
}

package ex1;

public class Ex4_Oper {
    public static void main(String[] args) {
        // 증감연산자 :1씩 증감하는 연산자
        //전치 : 증가부터 시켜놓고 실행
        //후치 : 실행한 후에 증가 시킴.
        int a = 10;
        int b = 10;
        int c = 0;
        System.out.println("a : " + (++a));
        System.out.println("b : " + (b++));
        System.out.println("b++ : " + b);
        System.out.println("c : " + (c++));
        System.out.println("c++ : " + c);
        int e = 1;
        System.out.println(e++);
        System.out.println(++e);                
    }
}

package ex1;

public class Ex5_Oper {
    public static void main(String[] args) {
        /* bit 단위로 연산하는 비트 연산자
        * &,|,^
        */
        int a =10;      // 1 0 1 0
        int b=7;        // 0 1 1 1
        int c=a&b;      // 0 0 1 0
        System.out.println("a&b 변수 c의 값 : " + c);
        // xor 두 비트 중 하나가 1이고 다른 하나는 0일 경우 연산 결과는 1
        
        c=a^b;
        // 1 0 1 0
        // 0 1 1 1
        // -------
        // 1 1 0 1
        System.out.println("a^b 변수 c의 값 : " + c);
        // ~논리부정 1 => 0, 0 => 1
        System.out.println("~c의 값 : " + (~c));
    }
}

package ex1;

public class Ex6_Oper {
    public static void main(String[] args) {
        int a=12;       // 0 0 0 0 1 1 0 0
        int b=2;
        // a: 비트 연산할 변수, b: 얼마나 쉬프트 할 것인지
        // b만큼 쉬프트 연산하라
        //                 0 0 0 0 1 1 0 0
        int c = a>>b;   // 0 0 0 0 0 0 1 1      2칸을 >> 방향으로 쉬프트 한것.
        int d = a<<b;   // 0 0 1 1 0 0 0 0      2칸을 << 방향으로 쉬프트 한것.
        System.out.println("12>>2 : " + c);
        System.out.println("12<<2 : " + d);
    }
}

package ex2;

public class Ex0_if {
    public static void main(String[] args) {
        int num = 1;
        
        // if() 조건에 만족 => true 실행이 된다.
        if (num > 9) {
            System.out.println("실행1");
        }
        System.out.println("실행2");       
        System.out.println("--------------------");
        
        // if() => false 일 경우 실행이 안되지만 else는 실행이 된다. 영역, 이것 아니면 저것(그외)
        if (num > 9) {
            System.out.println("9보다 크다");
        } else {
            System.out.println("9와 같거나 작다.");
        }        
        
        if (num > 9)
            System.out.println("9보다 크다");
        else System.out.println("9와 같거나 작다.");
    }
}

package ex2;

import java.util.Scanner;

public class Ex1_if {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("나이를 입력해 주세요 : ");
        int age = Integer.parseInt(sc.nextLine()); // 1. 16입력
        if (age <= 19) {        // 2. 조건 검사 => 16은 19보다 적기 때문에 true
                System.out.println("미성년자는 접근하실 수 없습니다."); // 3. 실행
                System.exit(0); // 시스템 종료
        } else {                // 2-1. 위의 조건 값이 false일 경우 무조건 실행
            System.out.println("축하합니다.");
        }
        System.out.println("여기는 회원 전용 컨텐츠입니다.");
        sc.close();
    }
}

package ex2;

public class Ex2_ifelse {
    // 학습포인트) if else를 사용했을때 지역변수 초기화의 개념을 파악한다.
    public static void main(String[] args) {
        int num = 10;
        int v;  // 초기화 하지 않음
        if ( num == 10) {
                v = 10;
                System.out.println(num + "월의 꽃");
                // 컴파일러가 if문은 수행이 안될 수도 있다고 인지해서
                // if문에만 초기화를 하면 컴파일 오류가 발생한다.
        } else {
                v = 20;
                System.out.println(num + "월의 꽃");
        }
        // if문 내에서 바꿔줘도 밖에서는 초기화가 안되어 있다.
        System.out.println(v + "");
        // 적어도 else 내에서 v값을 초기화 해줘야한다.
    }
}

package ex2;

public class Ex3_iflElse2 {

    public static void main(String[] args) {
        String str1 = new String("Test");
        String str2 = new String("Test");
        if (str1 == str2) {
            System.out.println("str1과 str는 주소가 같다.");
        } else {
            System.out.println("str1과 str는 주소가 다르다.");
        }
        if (str1.equals(str2)) {
            System.out.println("str1과 str는 내용이 같다.");
        } else {
            System.out.println("str1과 str는 내용이 다르다.");
        }
    }
}

package ex2;

import java.util.Scanner;

public class Ex4_ifElseif {
    // 모델을 만들어서 구현 해보기
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("과일 이름 : ");
        String val = sc.nextLine();
        String col = foodCheck(val);
        System.out.println(val + "은(는) " + col + "색입니다.");
        sc.close();
    }
    
    public static String foodCheck (String val) {
        String col = "";
        if(val.equals("사과")) {
                col = "Red";
        } else if (val.equals("바나나")) {
                col = "Yellow";
        } else if (val.equals("오렌지")) {
                col = "Orange";
        } else {
                col = "White";
        }
        return col;
    }
}

package ex2;

import java.util.Scanner;

public class Ex5_ifElseif {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("점수를 입력하세요 : ");
        int score = Integer.parseInt(sc.nextLine()); // 가점수 => 50
        String grade = "";  // grade를 출력하기 위해서 String 초기화
        if (score >= 50) { // true 이면
            grade = "고급";
        } else if (score >= 30) {
            grade = "중급";
        } else if (score >= 20) {
            grade = "초급";
        } else {
            grade = "없음";
        }
        System.out.println("점수 : " + score + " 점\n등급 : " + grade);
        sc.close();        
    }
}

package ex2;

import java.util.Scanner;

public class Ex5_ifElseif_Oper {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("점수를 입력하세요 : ");
        int score = Integer.parseInt(sc.nextLine());
        gradeCheck(score);
        sc.close();
    }
    
    private static void gradeCheck(int score) {
        String grade = "";
        if (score <= 100 & score >= 80) {
            grade = "고급";
        } else if (score < 80 && score >= 60) {
            grade = "중급";
        } else if (score < 60 && score >= 20) {
            grade = "초급";
        } else {
            grade = "없음";
        }
        System.out.println("점수 : " + score + " 점\n등급 : " + grade);
    }
}