[JAVA] TIL 004 - 23.07.17

유진·2023년 7월 17일

02_연산자(Operator)

* 연산자 종류와 우선 순위

  • %(mod) : 짝,홀수 구할 때 많이 사용
  • 상단 표에서 쉬프트, 비트는 보지 않기 -> 자바 : 인간친화(배우기 쉬운 언어)

* 증감 연산자

* 증감 연산자 : ++, --

피연산자의 값에 1을 더하거나 빼는 연산자로 위치에 따라 결과 값이 다르게 나타남

  • 전위 연산 : 먼저 연산 후 다른 연산 실행
    • 전위 연산자 예시
      int a = 10;
      int b = ++a;
      System.out.println(a + ", " + b); // 10, 11
  • 후위 연산 : 다른 연산 우선 실행 후 연산
    • 후위 연산자 예시
      int a = 10;
      int b = a++;
      System.out.println(a + ", " + b); // 10, 10

* 비교 연산자

데이터가 같은지, 다른지 비교할 때 쓰이며 항상 결과값은 논리 값(true, false)으로 나타남.

a == b : a와 b가 같으면 true

  • == 연산자 예시
    int a = 10;
    int b = 10;

    System.out.println(a == b); // true

a != b : a와 b가 다르면 true

  • != 연산자 예시
    double a = 1.23;
    double b = 3.14;

    System.out.println(a != b); // true

* 복합 대입 연산자

다른 연산자와 대입 연산자가 결합한 것으로
자기 자신과 연산 후 연산 결과를 자기 자신에게 누적 대입

 a += 10 // a = a + 10
 a -= 10 // a = a - 10
 a *= 10 // a = a * 10
 a /= 10 // a = a / 10
 a %= 10 // a = a % 10
  • 증감 연산과 비슷해 보이지만 증감연산자(++, --)는 1씩 증가
  • 대입 연산자는 원하는 값을 증가시키고 그 변수에 저장 가능

* 삼항 연산자 ( 리액트에서 많이 사용 )

조건식 ? 식1 : 식2;

조건식의 결과 값에 따라 연산을 처리하는 방식으로 결과 값이 참일 경우 식1, 거짓일 경우 식2 수행
삼항 연산자 안에 삼항 연산자를 중첩하여 쓰는 것도 가능

  • 삼항 연산자 예시
    int result1 = a > b ? a++ : b--;
    int result2 = a < b ? a++ : (b == 0 ? a-- : b++);
package edu.kh.op.ex;

import java.util.Scanner;

	public class OpExample { // 예제 코드 작성용 클래스

	// ex1() method : 객체 지향 프로그래밍에서 객체와 관련된 함수
    // -> OpExample이 가지고 있는 기능 중 ex1()이라는 기능
    public void ex1() {
    	// syso + ctrl + space 자동완성
        System.out.println("OpExample 클래스에 ex1() 기능 수행");
        System.out.println("클래스 분리 테스트");
        System.out.println("println 자동완성도 배웠어요~");
 	}
    
    
    public void ex2() {
    
    	Scanner sc = new Scanner(System.in);
        // 실행될 때 ExampleRun -> OpExample -> Scanner 순으로 만들어냄
        // Scanner는 같은 패키지내에 있지 않기 때문에 import(수입) 해와야한다.
        
        System.out.print("정수 입력 1 : ");
        int input1 = sc.nextInt(); // 다음 입력되는 정수를 읽어옴.
        
        System.out.print("정수 입력 2 : ");
        int input2 = sc.nextInt();
        
        System.out.printf("%d / %d = %d\n", input1, input2, input1 / input2);
        System.out.printf("%d %% %d = %d\n", input1, input2, input1 % input2);
        // %% : printf 에서 '%' 문자 출력하는 방법
    }
    
    
    public void ex3() {
    	// 증감(증가, 감소) 연산자 : ++, --
        // -> 피연산자(값)를 1 증가 또는 감소 시키는 연산자
        
        int iNum1 = 10;
        int iNum2 = 10;
        
        
        iNum1++; // iNum1 1증가
        iNum2--; // iNum2 1감소
        
        System.out.println("iNum1 : " + iNum1); // 11
        System.out.println("iNum2 : " + iNum2); // 9
        
        // 전위 연산 : ++3, --2 연산자가 앞쪽에 비치
        // -> 다른 연산자보다 먼저 증가/감소
        
        int temp1 = 5;
        
        System.out.println( ++temp1  +  5);
                            // ++5   +  5
                            // 6     +  5  ==  11
        
        System.out.println( "temp1 : " + temp1 ); // 6
        
        
        // 후위 연산 : 10++, 6-- 연산자가 뒤쪽에 배치
        // -> 다른 연산자보다 나중에 증가/감소
        
        int temp2 = 3;
        System.out.println( temp2--  +  2 ); // 5
                        //  3--      +  2 // 5
                        // temp2 -1; (1감소)
                        // temp2 는 ?
        
        System.out.println( "temp2 : " + temp2 ); // 2
        
        int a = 3;
        int b = 5;
        int c = a++  +  --b;
        
        //      3++  +  --5
        //  c = 3++  +   4
        //  c = 7
        
        // 미뤄놨던 a 후위연산 a++ ==> 3+1 == 4
        
        // 최종적으로 a,b,c 는 각각 얼마인가?
        System.out.printf("%d / %d / %d\n", a, b, c);
        // 4 / 4 / 7
    }
    
    
    public void ex4() {
    
    	// 비교 연산자 : >, <, >=, <=, ==, !=
        // - 비교연산자의 결과는 항상 논리값(true/false)
        // - 등호(=)가 포함된 연산자에서 등호는 항상 오른쪽!!
        
        // 같다 기호는 =, == ?
        // --> ==
        // 등호 1개(=) 대입 연산자로 사용
        //     --> 구분을 위해서 두개(==)를 "같다" 라는 의미로 사용
        
        int a = 10;
        int b = 20;
        
        System.out.println( a > b ); // false
        System.out.println( a < b ); // true
        System.out.println( a != b ); // true
        System.out.println( (a == b) == false ); // true
        				// () 괄호안에있는 것 먼저 연산
                        // false == false -> true
                        
        System.out.println("-------------------------------------");
        
        int c = 4;
        int d = 5;
        
        System.out.println( c < d ); // true
        System.out.println( c + 1 <= d ); // true
        				//  4 + 1 <= 5
                        // 산술 연산이 비교연산보다 우선순위가 높기 때문에
                        // 더하기 먼저 해야한다!
        
        System.out.println( c >= d - 1 ); // true
        
        System.out.println( (++c != d) == (--c != d) );
        				//  (++4 != 5) -> false
                        //                (--5 != 5) -> true
                        //  false == true
                        // -> false
                        
                        
        System.out.println("------------------------------");
        
        int temp = 723;
        
        System.out.println("temp는 짝수인가?" + (temp % 2 == 0) ); // false
        System.out.println("temp는 짝수인가?" + (temp % 2 != 1) ); // false
        
        System.out.println("temp는 홀수인가?" + (temp % 2 == 1) ); // true
        System.out.println("temp는 홀수인가?" + (temp % 2 != 0) ); // true
        
        System.out.println("temp는 3의 배수인가?" + (temp % 3 == 0) ); // true
        System.out.println("temp는 4의 배수인가?" + (temp % 4 == 0) ); // false
        System.out.println("temp는 5의 배수인가?" + (temp % 5 == 0) ); // false
    }
    
    public void ex5() {
    
    	// 논리 연산자 : &&(AND), ||(OR)
        
        
        // &&(AND) 연산자 : 둘 다 true면 true, 나머지는 false
        // 와, 그리고, ~면서, ~이면서, ~부터 ~까지, ~사이
        
        // ex) 사과와 바나나, 사과 그리고 바나나, 사과이면서 바나나
        
        int a = 101;
        
        // a는 100이상이면서 짝수인가?
        System.out.println( a >= 100 ); // a는 100 이상? true
        
        System.out.println( a % 2 == 0 ); // a는 짝수? false
        
    	System.out.println( (a >= 100) && (a % 2 == 0) ); // false
        
        
        int b = 5;
        
        // b는 1부터 10까지 숫자 범위에 포함되어 있는가?
        // ==> b는 1부터 10 사이의 숫자인가?
        // ==> b는 1보다 크거나 같으면서, 10보다 작거나 같은가?
        
        System.out.println( b >= 1 ); // b는 1 이상인가? true
        
        System.out.println( b <= 10 ); // b는 10 이하인가? true
        
        System.out.println( (b >= 1) && (b <= 10) ); // true
        
        
        System.out.println("-------------------------------------");
        
        
        // || (OR) 연산자 : 둘 다 false면 false, 나머지는 true (AND의 반대)
        // 또는, ~거나, ~이거나
        
        
        int c = 10;
        
        
        // c는 10을 초과 했거나 짝수인가?
        System.out.println( (c > 10) || (c % 2 == 0) ); // true
    }
    
    
    public void ex6() {
    
    	// 논리 부정 연산자 : !
        // -> 논리값을 반대로 바꾸는 연산자
        
        boolean bool1 = true;
        boolean bool2 = !bool1; // false
        
        
        System.out.println("bool1 : " + bool1); // true
        System.out.println("bool2 : " + bool2); // false
        
        System.out.println("----------------------------------");
        
        Scanner sc = new Scanner(System.in);
        
        // 정수를 하나 입력 받았을 때
        // 1) 해당 정수가 1부터 100사이 값이 맞는지 확인 (1이상 100이하)
        // 2) (반대) 1부터 100사이 값이 아닌지 확인
        
        System.out.print("정수 입력 : ");
        int input = sc.nextInt();
        
        // 1 <= input <= 100
        boolean result1 = 1 <= input && input <= 100;
        //				( input >= 1) && ( input <= 100)
        
        
        System.out.printf("%d은/는 1 이상, 100 이하의 정수인가? : %b\n", input, result1);
        
        // 1 이상 이면서 100 이하 <-> 1 미만 또는 100 초과
        boolean result2 = (input < 1) || (input > 100);
        
        boolean result3 = !( (input >= 1) && (input <= 100) );
        
        System.out.printf(%d은/는 1 미만, 100 초과 정수인가? : %b / %b\n", input, result2, result3);
    }
    
    public void ex7() {
    
    	// 복합 대입 연산자 : +=, -=, *=, /=, %=
        // -> 피연산자가 자신과 연산 후 결과를 다시 자신에게 대입
        
        int a = 10;
        
        // a를 1증가
        a++; // a = a + 1  a += 1
        System.out.println("a를 1 증가 : " + a); // 11
        
        // a를 4증가
        a += 4; // a = a + 4;
        System.out.println("a를 4 증가 : " + a); // 15
        
        // a를 10감소
        a -= 10; // a = a - 10;
        System.out.println("a를 10 감소 : " + a); // 5
        
        // a를 3배 증가
        a *= 3;
        System.out.println("a를 3배 증가 : " + a); // 15
        
        // a를 6으로 나눴을 때 몫
        a /= 6;
        System.out.println("a를 6으로 나눴을 때 몫 : " + a); // 2
        
        // a를 2로 나눴을 때 나머지
        a %= 2;
        System.out.println("a를 2로 나눴을 때 나머지 : " + a); // 0
    }
    
    
    public void ex8() {
    
    	// 삼항 연산자 : 조건식 ? 식1 : 식2
        
        // - 조건식의 결과가 true면 식1,
        //   false이면 식2를 수행하는 연산자
        
        
        // * 조건식 : 연산 결과가 true/false인 식
        //          (비교, 논리, 논리부정 연산이 포함)
        
        int num = 30;
        
        // num이 30보다 크면(초과) "num은 30보다 큰 수 이다."
        // 아니면 "num은 30 이하의 수이다" 출력
        
        String result = num > 30 ? "num은 30보다 큰 수 이다." : "num은 30 이하의 수이다";
                     // 조건식    ?
        // 반환값이 문자열이기 때문에 String으로 받음
        
        System.out.println(result); // num은 30 이하의 수이다
        
        
        System.out.println("=================================");
        
        // 입력 받은 정수가 음수인지 양수인지 구분
        // 단, 0은 양수로 처리
        
        // ex)
        // 정수입력 : 4
        // 양수 입니다.
        
        // 정수입력 : -5
        // 음수 입니다.
        
        Scanner sc = new Scanner(System.in);
        
        System.out.print("정수입력 : );
        int input = sc.nextInt();
        
        String str1 = "양수 입니다.";
  		String str2 = "음수 입니다.";
        
        String result2 = input >= 0 ? str1 : str2;
        
        System.out.println(result2);
    }
}
package edu.kh.op.ex;

public class ExampleRun { // 코드 실행용 클래스

	// 메인메서드 필수 작성
    public static void main(String[] args) {
    
    	// OpExample 생성
        //Scanner의 경우 다른 패키지에 있기 때문에 import를 해야함
        //Scanner sc = new Scanner(System.in);
        
        OpExample ex = new OpExample();
        // 같은 패키지 (edu.kh.op.ex) 안에 있는 클래스는
        // import를 하지 않아도 불러다 쓸 수 있다 (에러 X)
        
        //ex.ex1(); // ex가 가지고 있는 ex1() 메서드 실행
        //ex.ex2();
        //ex.ex3();
        //ex.ex4();
        //ex.ex5();
        //ex.ex6();
        //ex.ex7();
        //ex.ex8();
        
     }
}

문제 안내

Q.
기능 제공 클래스 : edu.kh.op.practice.OperatorPractice
기능 실행 클래스 : edu.kh.op.practice.PracticeRun
기능 제공 클래스에 여러 메소드를 작성하여 실습 진행

package edu.kh.op.practice;

public class PracticeRun {

	public static void main(String[] args) {
    
    OperatorPractice practice = new OperatorPractice();
    
    //practice.practice1();
	//practice.practice2();
    //practice.practice3();
}

실습문제1

Q.
메소드 명 : public void practice1(){}
모든 사람이 사탕을 골고루 나눠가지려고 한다. 인원 수와 사탕 개수를 키보드로 입력 받고 1인당 동일하게 나눠가진 사탕 개수와 나눠주고 남은 사탕의 개수를 출력하세요.
[실행화면]
인원 수 : 29
사탕 개수 : 100
1인당 사탕 개수 : 3
남는 사탕 개수 : 13

package edu.kh.op.practice;

import java.util.Scanner;

public class OperatorPractice {

	public void practice1() {
      Scanner sc = new Scanner(System.in);
      System.out.print("인원 수 : ");
      int input1 = sc.nextInt();

      System.out.print("사탕 개수 : ");
      int input2 = sc.nextInt();

      int result1 = input2 / input1;
      int result2 = input2 % input1;

      System.out.printf("1인당 사탕 개수 : %d\n", result1);
      System.out.printf("남는 사탕 개수 : %d\n", result2);
    }
}

실습문제2

Q.
메소드 명 : public void practice2(){}
키보드로 입력 받은 값들을 변수에 기록하고 저장된 변수 값을 화면에 출력하여 확인하세요.
ex.
이름 : 홍길동
학년(정수만) : 3
반(정수만) : 4
번호(정수만) : 15
성별(남학생/여학생) : 남학생
성적(소수점 아래 둘째 자리까지) : 85.75
3학년 4반 15번 홍길동 남학생의 성적은 85.75이다.

package edu.kh.op.practice;

import java.util.Scanner;

public class OperatorPractice {

	public void practice2() {
		Scanner sc = new Scanner(System.in);
		System.out.print("이름 : ");
		String input1 = sc.next();
		
		System.out.print("학년(정수만) : ");
		int input2 = sc.nextInt();
		
		System.out.print("반(정수만) : ");
		int input3 = sc.nextInt();
		
		System.out.print("번호(정수만) : ");
		int input4 = sc.nextInt();
		
		System.out.print("성별(남학생/여학생) : ");
		String input5 = sc.next();
		
		System.out.print("성적(소수점 아래 둘째 자리까지) : ");
		double input6 = sc.nextDouble();
		
		System.out.printf("%d학년 %d반 %d번 %s %s의 성적은 %.2f이다.\n", input2, input3, input4, input1, input5, input6);
    }
}

실습문제3

Q.
메소드 명 : public void practice3(){}
국어, 영어, 수학에 대한 점수를 키보드를 이용해 정수로 입력 받고,
세 과목에 대한 합계(국어+영어+수학)와 평균(합계/3.0)을 구하세요.
[실행화면]
국어 : 60
영어 : 80
수학 : 40
합계 : 180
평균 : 60.0

package edu.kh.op.practice;

import java.util.Scanner;

public class OperatorPractice {

	public void practice3() {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("국어 : ");
		int kor = sc.nextInt();
		
		System.out.print("영어 : ");
		int eng = sc.nextInt();
		
		System.out.print("수학 : ");
		int math = sc.nextInt();
		
		int sum = kor + eng + math; // 합계
		double avg = sum / 3.0; // 평균
		
		System.out.println("합계 : " + sum);
		System.out.printf("평균 : %.1f\n", avg);
		
		// 세 과목의 점수와 평균을 가지고 합격 여부를 처리하는데
		// 세 과목 점수가 각각 40점 이상이면서 평균이 60점 이상일 때 합격,
		// 아니라면 불합격을 출력하세요.
		
		boolean result = (kor >= 40) && (eng >= 40) && (math >= 40) && (avg >= 60);
		
		System.out.println(  result ? "합격" : "불합격"  );
    }
}

03_제어문

* 제어문

위에서 아래로 수행되는 프로그램의 흐름을 바꾸는 역할을 함

01. 조건문

프로그램의 수행 흐름을 바꾸는 역할을 하는 제어문 중 하나로 조건에 따라 다른 문장이 수행되도록 함

* if문




package edu.kh.control.condition;

import java.util.Scanner;

public class ConditionExample {

	public void ex1() {
    
    	// if문
        // 조건식이 true 일때만 내부 코드 수행
        
        /*
        * [작성법]
        * if(조건식) {
        * 		조건식이 true 일 때 수행할 코드
        * }
        *
        *
        */
        
        Scanner sc = new Scanner(System.in);
        
        System.out.print("정수 입력 : ");
        int input = sc.nextInt();
        
        // 입력된 정수가 양수인지 검사
        if(input > 0) {
        	System.out.println("양수입니다");
        }
        
        if(input <= 0) {
        	System.out.println("양수가 아니다.");
        }
    }
    
    
    public void ex2() {
    
    	// if - else 문
        // 조건식 결과가 true면 if문,
        // false면 else 구문이 수행됨.
        
        /*
        * if(조건식) {
        *		조건식이 true일 때 수행될 코드
        * } else {
        *		조건식이 false일 때 수행될 코드
        * }
        *
        *
        *
        */
        
        Scanner sc = new Scanner(System.in);
        
        // 홀짝 검사
        System.out.print("정수 입력 : ");
        int input = sc.nextInt();
        
        if( input % 2 != 0 ) {
        		System.out.println("홀수 입니다.");
                
        } else { // 짝수 또는 0 입력시 수행
        
        	// 중첩 if문
            if(input == 0) {
            	System.out.println("0 입니다.");
            } else {
            	System.out.println("짝수 입니다.");
            }
         }
    }
    
    
    public void ex3() {
    
    	// 양수, 음수, 0 판별
        
        // if - else if - else
        
        Scanner sc = new Scanner(System.in);
        
        System.out.print("정수 입력 : ");
        int input = sc.nextInt();
        
        if(input > 0) { // input이 양수일 경우
        	System.out.println("양수 입니다.");
        
        } else if(input < 0) { // input이 음수일 경우
       		// 바로 위에있는 if문이 만족되지 않은 경우 수행
            System.out.println("음수 입니다.");
            
        } else {
        	System.out.println("0 입니다.");
        
        }
    }
    
    
    public void ex4() {
    
    	// 달(month)을 입력받아 해당 달에 맞는 계절 출력
        // 단, 겨울일때 온도가 -15도 이하 "한파 경보", -12이하 "한파 주의보"
        // 여름일때 온도가 35도 이상 "폭염 경보", 33도 이상 "폭염 주의보"
        // 1~12 사이가 아닐땐 "해당하는 계절이 없습니다" 출력
        
        Scanner sc = new Scanner(System.in);
        
        System.out.print("달 입력 : ");
        int month = sc.nextInt();
        
        int temperature = 34;
        
        String season; // 아래 조건문 수행 결과를 저장할 변수 선언
        
        if(month == 1 || month == 2 || month == 12) {
        	season = "겨울";
            
            if(temperature <= -15) {
            	//season = "겨울 한파 경보";
                season += " 한파 경보";
                //season = season + " 한파 경보"
            } else if(temperature <= -12) {
            	season += " 한파 주의보";
            }
            
        } else if(month >=3 && month <=5) {
        	season = "봄";
        } else if(month >=6 && month <=8) {
        	season = "여름";
            
            if(temperature >= 35) {
            	season += " 폭염 경보";
            } else if(temperature >= 33) {
            	season += " 폭염 주의보";
            }
        } else if(month >=9 && month <= 11) {
        	season = "가을";
        } else {
        	season = "해당하는 계절이 없습니다.";
        }
        
        System.out.println(season);
    
    }
    
    
    public void ex5() {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("나이 입력 : ");
		int age = sc.nextInt();
		
		if(age <= 13) {
			System.out.println("어린이 입니다.");
		} else if((age > 13) && (age <= 19)) {
			System.out.println("청소년 입니다.");
		} else {
			System.out.println("성인 입니다.");
		}
	}
	
	
	public void ex6() {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("점수 입력 : ");
		int score = sc.nextInt();
		
		if(score >= 90 && score <= 100) {
			System.out.println("A");
		} else if(score >= 80 && score < 90) {
			System.out.println("B");
		} else if(score >= 70 && score < 80) {
			System.out.println("C");
		} else if(score >= 60 && score < 70) {
			System.out.println("D");
		} else if(score < 60 && score >= 0) {
			System.out.println("F");
		} else {
			System.out.println("잘못 입력하셨습니다");
		}
	}
	
	public void ex7() {
		
		 Scanner sc = new Scanner(System.in);
		 
		 System.out.print("나이 : ");
		 int age = sc.nextInt();
		 
		 System.out.print("키 : ");
		 double height = sc.nextDouble();
		 
		  if(age >= 12 && age <= 100) {
			 if(height >= 140) {
				 System.out.println("탑승 가능");
			 } else {
				 System.out.println("적정 키가 아닙니다.");
			 }
		  } else if(age < 12 && age >= 0) {
			  System.out.println("적정 연령이 아닙니다.");
		  } else {
			  System.out.println("잘못 입력 하셨습니다.");
		  }
	}
	
	
	public void ex8() {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.print("나이 : ");
		int age = sc.nextInt();
		
		if(age < 0 || age > 100) {
			System.out.println("나이를 잘못 입력 하셨습니다.");
			return;
		}
		
		System.out.print("키 : ");
		double height = sc.nextDouble();
		
		if(height < 0 || height > 250) {
			System.out.println("키를 잘못 입력 하셨습니다.");
			return;
		}
		
		if(age >= 12 && age <= 100) {
			if(height < 140 && height >= 0) {
				System.out.println("나이는 적절하나, 키가 적절치 않음");
			} else {
				System.out.println("탑승 가능");
			}
		} else if(age < 12 && age >= 0) {
			if(height >= 140 && height <= 250) {
				System.out.println("키는 적절하나, 나이는 적절치 않음");
			} else {
				System.out.println("나이와 키 모두 적절치 않음");
			}
		}
	}
}
package edu.kh.control.condition;

public class ConditionRun {
	
	public static void main(String[] args) {
		
		ConditionExample condition = new ConditionExample();
		
		//condition.ex1();
		//condition.ex2();
		//condition.ex3();
		//condition.ex4();
		//condition.ex5();
		//condition.ex6();
		//condition.ex7();
		//condition.ex8();
	}

}

0개의 댓글