JAVA 기초(3) 연산자

Dayon·2023년 11월 6일
0

자바-기초다지기

목록 보기
3/6
post-thumbnail

🧮  1. 산술 연산자


기본 산술 연산자

(+) 더하기 , (-) 빼기 , (*) 곱하기, (/) 나누기, (%) 나머지

  • 산술 연산자 예제 #1

    public class Code3_1 {
        public static void main(String[] args) {
            int n1, n2 , res ;
            n1 = 5 ;
            n2 = 3 ;
            res = n1 + n2 ;
            System.out.println(res) ; 
        }
    }
  • 산술 연산자 예제 #2

    public class Code3_2 {
        public static void main (String[] args) {
            int n1, n2, res ; 
            n1 = 5 ;
            n2 = 3 ; 
            res = n1 + n2 ;
            System.out.println(res);
            res = n1 - n2 ;
            System.out.println(res);
            res = n1 * n2 ;
            System.out.println(res);
            res = n1 / n2 ;
            System.out.println(res);
            res = n1 % n2 ;
            System.out.println(res);
        }
    }

산술 연산자의 우선 순위

  • 하나의 연산에 여러개의 연산자가 있는 경우

( → 연산자의 우선순위가 정해져 있어야 정확한 계산 결과를 산출할 수 있음)

  • 연산자의 우선순위가 동일한 경우
    public class Code3_3 {
        public static void main(String[] args) {
            int a = 3, b = 4, c = 5; 
            System.out.println(a + b - c);    // 2
            System.out.println(a - c + b);    // 2
            System.out.println( -c + a + b);  // 2
        }
    }
  • 연산자의 우선순위가 다른 경우
    public class Code3_3 {
        public static void main(String[] args) {
            int a = 3, b = 4, c= 5; 
            System.out.println(a * b + c);    // 17
            System.out.println(c + a * b);    // 17
        }
    }

제곱 연산

`Math.pow(밑수, 지수)`

public class Code3_6 {
    public static void main(String[] args) {
        double num ;
        num = Math.pow(3,2);
        System.out.println(num);    // 3^2 = 9.0
        num = Math.pow(4,3);
        System.out.println(num);    // 4^3 = 64.0
    }
}

Math 클래스

  1. Math.pow(밑수,지수)
  2. Math.abs() : 절대값
  3. Math.log() : 로그값
  4. Math.max() : 최대값
  5. Math.min () : 최솟값
  6. Math.sin(), Math.cos() , Math.tan() : 삼각함수

👽 2. 대입 연산자


대입 연산자 개념

대입 연산자(=) 는 오른쪽의 값이나 계산 결과를 왼쪽의 변수에 대입함

(=)의 왼쪽에는 변수가 1개여야 함

  • 대입 연산자 예제
    public class Code3_7 {
        public static void main(String[] args) {
            int num ; 
            num = 100 ;
            num = 100 * 200 ;
            num = Integer.parseInt("100") + Integer.parseInt("200");
        }
    }

복합 대입 연산자 - 변수의 값을 변경한 후에 이를 자신에게 대입함

public class Code3_8 {
    public static void main(String[] args) {
        int num ;
        num = 100 ; 
        num = num + 200 ;  // num += 200 과 동일 
        System.out.println(num) ;  // 300
    }
}

+= , -= , *=, /= , %=

증감 연산자

++ : 변수의 값이 1씩 증가한다 . num++ , num += 1 , num = num + 1 모두 동일한 의미

- -: 변수의 값이 1씩 감소한다

  • 복합 대입 연산자 예제
    public class Code3_9 {
        public static void main (String[] args){
            int num = 20 ;
            num ++ ; 
            System.out.println(num + " ");
    
            num -- ; 
            System.out.println(num + " ");
    
            num += 3 ; 
            System.out.println(num + " ");
    
            num -= 3 ; 
            System.out.println(num + " ");
    
            num *= 3 ; 
            System.out.println(num + " ");
    
            num /= 3 ; 
            System.out.println(num + " ");
    
            num %= 3 ; 
            System.out.println(num + " ");
        }
    }
  • 편의점의 일일 매출 계산하기
    public class Code3_lab {
        public static void main(String[] args){
    
            int total = 0 ; 
    
            int coffee = 500 , coffeeP = 1800 ;
            int kimbap = 900 , kimbapP = 1400 ; 
            int bmilk = 800 , bmilkP = 1800 ;
            int dosilak = 3500 , dosilakP = 4000 ;
            int cola = 700, colaP = 1500 ;
            int snack=1000, snackP = 2000 ; 
    
            total -= kimbap*10;
            total += bmilkP*2;
            total -= dosilak*5;
            total += dosilakP * 4;
            total += colaP;
            total += snackP*4 ;
            total += coffeeP*5 ; 
    
            System.out.println("오늘의 총 매출액은 " + total + "원 입니다.");
    
        }
    }

💪🏽  3. 비교 연산자와 논리 연산자


비교 연산자의 개념

  • 어떤 것이 큰지 , 작은지, 같은지를 비교하는 연산자고, 관계 연산자라고도 불름

  • 비교 연산자의 결과 : yes 또는 true 참, no 또는 false(거짓)


비교연산자의 종류

비교연산자의미설명
==같다왼쪽값과 오른쪽 값이 같으면 참
! =같지 않다왼쪽값과 오른쪽 값이 다르면 참
>크다왼쪽 값이 오른쪽 값보다 크면 참
<작다왼쪽 값이 오른쪽 값보다 작으면 참
> =크거나 같다왼쪽 값이 오른쪽 값보다 크거나 같으면 참
< =작거나 같다왼쪽 값이 오른쪽 값보다 작거나 같으면 참

비교 연산자의 활용

  • 운전면허 필기 시험 점수를 입력받아 70점 이상이면 합격 (True), 그렇지 못하면 불합격(False)으로 처리하는 프로그램
    import java.util.Scanner;
    
    public class Code3_10 {
        public static void main (String[] args){
            Scanner s = new Scanner(System.in);
            int score ; 
    
            System.out.println("시험점수를 입력하세요. ");
            score = s.nextInt();
    
            System.out.println(score>=70);
            // if (score >= 70) {
            //     System.out.println("합격입니다");
            // } else {
            //     System.out.println("불합격입니다.");
            // }
    
            s.close() ; 
        }
    }
  • 비교 연산자 예제 2
    • print() 에는 개행 문자가 없고, println()은 개행문자 포함

      public class Code3_11 {
          public static void main(String[] args) {
              int n1 = 100, n2 = 200 ; 
      
              System.out.print(n1 == n2);
              System.out.println(n1 != n2);
      
              System.out.print(n1>n2);
              System.out.println(n1<n2);
      
              System.out.print(n1>=n2);
              System.out.println(n1<=n2);
          }
      }
  • 비교연산자 (==) 와 대입연산자 (=)
    • n1 = n2 는 n2의 값을 n1에 대입

    • n1 == n2 는 같은지 확인하는 비교 연산자


논리 연산자의 개념

논리 연산자 : 비교 연산자가 여러 번 필요할 때 사용함

논리 연산자의미설명사용 예
&&그리고, and둘다 참이어야지 참(num > 10) && (num < 20)
ㅣㅣ또는 or둘 중에 하나만 참이어도 참(num == 10) ㅣㅣ (num==20)
!부정 not참이면 거짓 거짓이면 참!(num<100)
  • num의 값이 10과 20 사이인 경우
    • 조건1 ) num은 10보다 커야 함

    • 조건2 ) 그리고 num은 20보다 작아야 함

      ( num > 10 ) && ( num < 20 )

  • 논리 연산자 예제
    public class Code3_12 {
        public static void main(String[] args){
            int num = 99;
    
            System.out.println( (num > 100) && (num < 200) );   // 100~200 사이 (X)
            System.out.println( (num == 99) || (num == 100) );  // 99 이거나 100 (0)
            System.out.println( !(num == 100) );                // 100이 아니다 (0)
        }
    }

🥇  4. 연산자의 우선순위


연산자의 우선 순위

한 줄에 여러 연산자가 동시에 들어가는 경우

  1. [1차 연산자] "( )" [ ] .
  2. [단항 연산자] +, -, ++ - -, ~ !
  3. [산술 연산자] *, / , %
  4. [산술 연산자] + , -
  5. [비트 시프트 연산자] << , >> , >>>
  6. [비교 연산자] < , < = , > , > =
  7. [비교 연산자] == , ! =
  8. [비트 연산자] &
  9. [비트 연산자] ^
  10. [비트 연산자] |
  11. [논리 연산자] &&
  12. [논리연산자] ||
  13. [조건 삼항 연산자] ?
  14. [대입 연산자] = , +=, -=, /=, *=, %=, &=, ^=, |=, << =, >> =

기말 평균 학점 구하기

public class Code3_lab2 {
    public static void main(String[] args){
        double avgscore ; 

        int java = 3, mobile = 2, excel = 1 ;
        double B = 3.5 , A0 = 4.0 , A = 4.5 ; 

        avgscore = ( (java * B) + (mobile * A0) +(excel * A) ) / (java + mobile + excel) ;
        avgscore = Math.round(avgscore*100.0)/100.0 ; // 소수점 2자리까지 출력 

        System.out.println("평균 학점 : " + avgscore);
    }
}
profile
success is within reach, allow yourself time

0개의 댓글