ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 04. 연산자 & 제어문
    멋사 부트캠프/Java 프로그래밍 2025. 3. 10. 19:04

    * 기본 연산자

    📌 Java 연산자 종류 정리

    연산자 종류연산자설명예제결과

    산술 연산자 + 덧셈 5 + 3 8
      - 뺄셈 5 - 3 2
      * 곱셈 5 * 3 15
      / 나눗셈 5 / 2 2 (정수 나눗셈 결과는 정수)
      % 나머지 5 % 2 1
    대입 연산자 = 값 할당 int x = 10; x = 10
      += 덧셈 후 대입 x += 5; x = x + 5
      -= 뺄셈 후 대입 x -= 3; x = x - 3
      *= 곱셈 후 대입 x *= 2; x = x * 2
      /= 나눗셈 후 대입 x /= 2; x = x / 2
      %= 나머지 후 대입 x %= 2; x = x % 2
    비교 연산자 == 같음 5 == 3 false
      != 다름 5 != 3 true
      > 초과 5 > 3 true
      < 미만 5 < 3 false
      >= 이상 5 >= 5 true
      <= 이하 5 <= 3 false
    논리 연산자 && AND (둘 다 true이면 true) (5 > 3) && (10 > 5) true
      `   ` OR (둘 중 하나라도 true이면 true)
      ! NOT (true → false, false → true) !(5 > 3) false
    증감 연산자 ++ 1 증가 int x = 5; x++; x = 6
      -- 1 감소 int x = 5; x--; x = 4
    비트 연산자 & 비트 AND 5 & 3 (0101 & 0011) 1 (0001)
      ` ` 비트 OR `5
      ^ 비트 XOR 5 ^ 3 (0101 ^ 0011) 6 (0110)
      ~ 비트 NOT ~5 (~0101) -6
      << 왼쪽 시프트 5 << 1 (0101 → 1010) 10
      >> 오른쪽 시프트 5 >> 1 (0101 → 0010) 2
      >>> 부호 없는 오른쪽 시프트 -5 >>> 1 양수 값
    삼항 연산자 조건 ? 참 : 거짓 조건에 따라 값 선택 (5 > 3) ? "Yes" : "No" "Yes"
    instanceof 연산자 instanceof 객체의 타입 확인 "Hello" instanceof String true

     

    1. 반복문

    정의 : 어떤 행위를 반복하거나, 어떤 배열의 인자를 패턴을 이용하여 색인할 때, 사용한다.

    종류 : for, foreach, while, do while

     

    일반 For사용 예시) 

    //(1) For 문
    private static void arrayPrn(int[] ar) {
    		ar[0] = 1000;
    		
    		System.out.println("====== ar for문 출력 =======");
    		for(int i=0; i < ar.length; i++) {
    			System.out.println(ar[i]);
    		}
    }
    
    //(2)For-Each문
    int[][] arr2 = {
                {5, 5, 5, 5, 5},
                {10, 10, 10, 10, 10},
                {20, 20, 20, 20, 20},
                {30, 30, 30, 30, 30},
            };
            int sum = 0;
            int cnt = 0;
    
            for(int[] res : arr2) {
                for(int i : res) {
                    sum += i;
                    cnt++;
                }
     }
     
    //(3)While 문
    private static void test04() {
    		int i = 1;
    		int cnt = 0;
    		
    		while (i <= 100) {					// 무한루프를 지정하게 되면 조건문을 지정해서 멈춤.
    			if(i%5 == 0) {
    				System.out.printf("%5c \n", '*');
    				cnt++;
    			}
    			else {
    				System.out.printf("%5d ", i);
    			}
    			i++;
    		}
    		System.out.println();
    		System.out.println("* 개수 : " + cnt);
    	}
    }
    
    //(4)do-While문
    public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int i = 1;
    		int count = 1;
    		
    		System.out.print("how many print : ");
    		count = sc.nextInt();
    		
    		do {
    			System.out.println(i);
    			i++;
    		} while(i <= count);
    }

     

     

    2. 조건문

    정의 : 어떤 변수에 대해, 참/거짓을 조건 판별할 때, 사용한다. (세부 정의 시)

    종류 : if 문, 삼항 연산자( [조건식] ? " true " : " false ")

    연산자 : &&, ||, ==, !=, ! 를 주로 이용

     

    public static void main(String[] args) {
    		Scanner sc = new Scanner(System.in);
    		int[] score = new int[4];
    		int sum = 0;
    		double avg = 0.0;
    		
    		for(int i=0; i < args.length; i++) {
    			score[i] = Integer.parseInt(args[i]);
    		}
    		
    		sum = calcSum(score[0], score[1], score[2], score[3]);
    		avg = sum / args.length;
    		
    		System.out.println("sum : " + sum);
    		System.out.println("avg : " + avg);
    		
    		if(avg >= 90 && avg <= 100) {
    			System.out.println("A 학점");
    		}
    		else if(avg >= 70 && avg < 90) {
    			System.out.println("B 학점");
    		}
    		else if(avg >= 50 && avg < 70) {
    			System.out.println("C 학점");
    		}
    		else if(avg >= 30 && avg < 50) {
    			System.out.println("D 학점");
    		}
    		else {
    			System.out.println("F 학점");
    		}
    		
    	}
    public static int calcSum(int a, int b, int c, int d) {
    	return a+b+c+d;
    }

     

    3. 선택문

    정의 : 어떠한 변수/값을 받았을 때, 직관적으로 분기하기 위하여 사용한다. (정수형만 입력받을 수 있다)

    종류 : switch-case, generic switch-case

     

    //(1) switch-case 문
    public static void switchTest01(){
    		Scanner sc = new Scanner(System.in);
    		int month = 0;
    		
    		System.out.print("원하는 달을 입력 : ");
    		month = sc.nextInt();
    		
    		switch(month) {
    			case 12 :  
    			case 1 : 
    			case 2: System.out.println("겨울"); break;
    			case 3:
    			case 4: 
    			case 5: System.out.println("봄"); break;
    			case 6: 
    			case 7: 
    			case 8: System.out.println("여름"); break;
    			case 9: 
    			case 10:
    			case 11: System.out.println("가을"); break;
    			
    			default : System.out.println("원하는 달이 없습니다.");
    } //switch end
    
    //(2) Generic Switch-Case문
    private static void PatternSwitchExample() {
    		// 1) :break;를 화살표 레이블(->)로 대체
    		// 2) 표현식을 간략하게 지정함.
    		// 3) when 문 사용
    		// 4) null을 사용할 수 있다.
    		
    		Object obj = 97;
    		
    		switch (obj) {
    			//조건 판별(intger) 
    			case Double d -> System.out.println("실수 : " + d);
    			case Integer i when i > 10 -> System.out.println("10보다 큰 정수");
    			case Integer i -> System.out.println("정수 : " + i);
    		
    			case String s -> System.out.println("문자열 : " + s);
    			case null -> System.out.println("Null 값이 입력되었습니다.");
    			default -> System.out.println("others"); 
    		}
    }

     

Designed by Tistory.