Operator (연산자)

Zino·2022년 12월 7일

Java

목록 보기
2/26
post-thumbnail

연산자 (Operator)

단항 연산자

논리 부정 연산자 : !

  • 논리 값을 부정하여 반대 값으로 변경
    제어문을 활용할 때 많이 쓰임

논리 부정 연산자 예시

boolean bool1 = true;
boolean bool2 = !bool1;
System.out.println(bool2); // false

증감 연산자 : ++, --

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

전위 연산 : 먼저 연산 후 다른 연산 실행
후위 연산 : 다른 연산 우선 실행 후 연산

전위 연산자 예시

int a = 10;
int b = ++a;
System.out.println(a + ", " + b);

후위 연산자 예시

int a = 10;
int b = a++;
System.out.println(a + ", " + b);

산술 연산자

  • 일반 수학과 동일한 연산 방법, 우선순위. 단, %는 나누기의 나머지 값을 구하는 연산

* / % 연산자 예시

int a = 10, b = 20, c = 0;
c = a * b;
c = a / b;
c = a % b;

‘/’ 연산 시 형 변환에 유의해야 함

+ - 연산자 예시

int a = 10, b = 20, c = 0;
c = a + b;
c = a - b;

비교 연산자

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

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

== 연산자 예시

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

!= 연산자 예시

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

비교 연산자

  • 두 피연산자의 값의 크기 비교
  • 기본형 boolean과 참조형을 제외하고 나머지 자료형에 모두 사용 가능

비교 연산자 예시

if(a < b) {}
int result = a > b ? a++ : b--;
for(int a = 0; a <= b; a++) {}
while(a >= b) {}

논리 연산자

  • 논리 값 두 개를 비교하는 연산자

&& : 두 피연산자가 모두 true일 때 true 반환 (AND)
|| : 두 피연산자 중 하나만 true여도 true 반환 (OR)

복합 대입 연산자

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

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++);

예제 1

입력

public class OpExample {
	
	//기능 메소드 method : 객체 지향 프로그래밍에서 
	// 객체와 관련된 서브루틴 or 함수
	public void ex1() {
		// void : return 값이 없는 메소드에 작성 
		System.out.println("OpExamle 클래스에" 
		                 + "ex1() 기능 수행");
	}
	// tip : 하나의 메소드 안에는 하나의 기능만 정의해야함.
	public void ex2() {
		int iNum1 = 10;
		int iNum2 = 10;
		
		iNum1++;
		iNum2--;
		
		System.out.println("iNum1: " + iNum1);
		System.out.println("iNum2: " + iNum2);		
	}
	public void ex3() {
		//전위연산 : ++3, --2 연산자가 앞쪽에 배치 
		// -> 다른 연산자보다 먼저 증감/감소 
		int temp1 = 5;
		System.out.println(++temp1 + 5);
				         // = >  6 + 5 == 11
		
		//후위연산 : 10++ , 6-- 연산자가 뒤쪽에 배치
		// -> 다른 연산자보다 나중에 증가 / 감소
		
		int temp2 = 3;
		System.out.println(temp2-- + 2);//5
			// 3 + 2 = 5
			// temp2 <= 2(1감소)

		System.out.println(temp2);
		
	}
	public void ex4() {
		// 비교연산자: > , < , >= , <= , == , !=
		// - 비교연산자의 결과는 항상 논리감 (true/false)
		// - 등호(=)가 포함된 연산자에서 등호는 항상 오른쪽!
		
		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
		
		int c = 4;
		int d = 5;
		
		System.out.println( c + 1 <= d );//true
						// 산술연산이 비교연산보다 우선순위 높다!!
		
		int temp = 723;
		System.out.println("temp는 짝수?" + (temp % 2 == 0)); //false
		
		
		
		
	}
	
	public void ex5() {
		
		// 논리연산자 : &&(and), ||(or)
		// && : 둘다 true 이면 true 
		
		int a = 101;
		// a는 100 이상이면서 짝수인가 ?
		System.out.println((a >= 100) && (a % 2 ==0)); // false
		
		// || : 둘중 하나가 true 이면 true , 둘다 false 면 false 
		int c = 10;
		System.out.println((c > 10) || (c % 2 == 0)); //true
												
		
	}
	
	public void ex6() {
		//논리 부정 연산자 : ! 
		//논리값을 반대로 바꾸는 연산자 
		
		boolean bool1 = true;
		System.out.println(!bool1);
		}
	public void ex7() {
		// 복합 대입 연산자 : +=, -= ,*= ,/= %=
		// => 피연산자가 자신과 연산 후 결과를 다시 자신에게 대입
		
		int a = 10;
		
		a++; // 11
		
		System.out.println("a++ : " + a);
		
		a += 4; //15
		//a = a + 4
		System.out.println("a +=4 : " + a);
		
		a -= 10;
		
		System.out.println("a -= 10 : " + a);
		
		a *= 3;
		
		System.out.println("a *= 3 : " + a);
		
		a /= 6;
		
		System.out.println("a /= 6 : " + a);
		
		a %= 2; 
		
		System.out.println("a %= 2 : " + a);
	}
	public void ex8() {
		// 삼항 연산자 
		// 조건식 ? 식1 : 식2 : 
		// 조건식 결과가 true 식1 , false 식2
		int num = 30;
		String str1 = "num은 30 보다 크다";
		String str2 = "num은 30 이하다";
		
		String result = num > 30 ? str1 : str2;
		System.out.println(result);
		
		
	}
	
}

출력

true
true
temp는 짝수?false
false
true
false
a++ : 11
a +=4 : 15
a -= 10 : 5
a *= 3 : 15
a /= 6 : 2
a %= 2 : 0
num은 30 이하다

예제 2

public class OperatorPractice {
		
	public void  practice1() {
		/*
		 * 모든사람이 사탕을 골고루 나눠가지려고 한다 .
		 * 인원 수와 사탕 개수를 키보드로 입력을 받고
		 * 1인당 동일하게 나눠가진 사탕 개수와 
		 * 나눠주고 남은 사탕의 개수를 출력하세요.
		 * 
		 * [실행화면]
		 * 인원 수 :29
		 * 사탕 개수 :100
		 * 1인당 사탕 개수 :3
		 * 남는 사탕 개수 : 13*/
		
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("인원수 : ");
		int input1 = scanner.nextInt();
		System.out.print("사탕 개수 : ");
		int input2 = scanner.nextInt();
		
		System.out.println();
		System.out.println("1인당 사탕 개수 : " + input2 / input1);
		System.out.println("남은 사탕 개수 : " + input2 % input1);
		
		
	}
	public void practice2() {
		
		/*
		 * 키보드로 입력 받은 값들을 변수에 기록하고
		 * 저장된 변수 값을 화면에 출력하세요
		 * ex.
		 * 이름 :홍길동
		 * 학년(정수만) :
		 * 반(정수만) :
		 * 번호(정수만) : 15
		 * 성별(남학생/여학생) : 남학생
		 * 성적(소수점 아래 둘째 자리까지) : 85.75
		 * 3학년 4반 15번 홍길동 남학생의 성적은 85.75이다.
		 *
		 * */
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("이름  : ");
	    String input3 = scanner.next();
	    
	    System.out.print("학년(정수만) : ");
	    int input4 = scanner.nextInt();
	    
	    System.out.print("반(정수만) : ");
	    int input5  = scanner.nextInt();
	   
	    System.out.print("번호(정수만) : ");
	    int input6  = scanner.nextInt();
	    
	    System.out.print("성별(남학생/여학생) : ");
	    String input7 = scanner.next();
	   
	    System.out.print("성적(소수점 아래 둘째 자리까지) : ");
	    float input8 = scanner.nextFloat();
	    
	    
	    //System.out.println(input3 + "학년 " + input4 + "반 " + input5 + "번호 " + input3 + input7
	    		 //+ "의 " +"성적은 "  + input8 + "이다.");
	    System.out.printf("%d학년 %d반 %d번 %s %s의 성적은 %.2f점 입니다.",
	    				input4, input5 , input6 , input3 , input7 , input8 );	    
	}
	public void practice3() {
		/*
		 * 국어, 영어, 수학에 대한 점수를 키보드를 이용해 정수로 입력 받고, 세 과목에 대한 합계와 평균을 구하세요.
		 * [실행화면]
		 * 국어 :60
		 * 영어 :80
		 * 수학 :40
		 * 합계 :180
		 * 평균 :60.0*/
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("국어 : ");
		int input9 = scanner.nextInt();
		
		System.out.print("영어 : ");
		int input10 = scanner.nextInt();
		
		System.out.print("수학 : ");
		int input11 = scanner.nextInt();
		
		int sum = input9 + input10 + input11; // 합계
		double avg = sum / 3.0 ; //평균
		System.out.println("합계 : " + sum);
		System.out.printf("평균 : %.1f " , avg);
		
		
		// 세 과목의 점수와 평균을 가지고 합격 여부를 처리하는데
				// 세 과목 점수가 각각 40점 이상이면서 평균이 60점 이상일 때 합격,
				// 아니라면 불합격을 출력하세요.
		
		boolean result = (input9 >= 40) && (input10 >= 40) && (input11 >= 40) 
				&&(avg >= 40);
		
		System.out.println();
		System.out.println(result ? "합격" : "불합격");
							//조건식 ? 식1 :식2
		}
	
		
}
profile
Willingness to be a fool!

0개의 댓글