07 Boolean Expressions

이성준·2023년 7월 21일

Java Notes

목록 보기
5/5

Boolean Expressions

return type이 boolean 곧 true,false를 내놓는 함수를 predicate이라고 합니다.

predicate logic (술어 논리)의 predicate을 말합니다.

2는 짝수라는 참인 명제(proposition)에서 2를 미지수 x로 두고 술어를 분리하면 'x는 짝수'인지를 판별하는 함수 곧 predicate이 됩니다.

Equality, Relational Operator

Equality, Relational Operator는 모두 predicate

operatordescription
==equal to
!=not equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to

ComparisonDemo 연습

class ComparisonDemo {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if(value1 == value2)
            System.out.println("value1 == value2");
        if(value1 != value2)
            System.out.println("value1 != value2");
        if(value1 > value2)
            System.out.println("value1 > value2");
        if(value1 < value2)
            System.out.println("value1 < value2");
        if(value1 <= value2)
            System.out.println("value1 <= value2");
    }
}

Output:

value1 != value2
value1 <  value2
value1 <= value2

ConditionalDemo

Conditional Operator로 복잡한 boolean expression을 조립할 수 있습니다.

class ConditionalDemo1 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}
class ConditionalDemo2 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}

Questions and Exercises: Operators을 풉니다.

Questions

  1. Consider the following code snippet.
	arrayOfInts[j] > arrayOfInts[j+1]
	Q. Which operators does the code contain?
    -> 이 코드에는 어떤 연산자가 있습니까?
				
    A. > , +
  1. Consider the following code snippet.
	int i = 10;
    int n = i++%5;
	2-a. What are the values of i and n after the code is executed?	
    -> 코드가 실행된 이후, i 와 n 의 값은?
    	A. `i = 11` , `n = 2`
    
	2-b. What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?
    -> 후위연산자(i++) 대신 전위연산자(++i)를 사용했을 때, i 와 n의 값은 ?
   		A. `i = 11` , `n = 3`
        
  1. To invert the value of a boolean, which operator would you use?
    -> boolean 값을 반전시키려면, 어떤 연산자를 사용하는지?
    A. ! operator
  2. Which operator is used to compare two values, = or == ?
    -> 두 값을 비교할 때, = 혹은 == 중 어떤 연산자를 사용하는지?
    A.== operator
  3. Explain the following code sample: result = someCondition ? value1 : value2;
    -> result = someCondition ? value1 : value2; 에 대해 설명해보아라'
    A. someCondition 이 true 이면, result의 값 는 value1 이다. 반대로 false이면 result는 value2 이다.

연습 Practice

if를 쓰지 않고 풉니다.

majority

boolean 값을 셋 받아서 true가 둘보다 많으면 true 아니면 false라 답하는 MajorityTest.majority를 정의합니다.
command line에서 세 String을 받아 boolean 값으로 바꾸고 majority를 판단하는 application으로 고칩니다. Boolean.parseBoolean(String)을 씁니다.

class MajorityTest{
    static boolean majority(boolean first, boolean second, boolean third){
        int count = 0;
        
        count += first ? 1 : 0;

        count += second ? 1 : 0;

        count += third ? 1 : 0;

        return count > 2;
    }

    public static void main(String[] args) {
        boolean first = Boolean.parseBoolean(args[0]);
        boolean second = Boolean.parseBoolean(args[1]);
        boolean third = Boolean.parseBoolean(args[2]);

        System.out.format("Majority : %b", majority(first, second, third));
    }
}

even

짝수를 판별하는 predicate Mathx.even을 구현하고 TestMathx.testEven()에서 Mathx.random으로 뽑은 int 값으로 test합니다.
홀수를 판별하는 Mathx.odd도 만들어 같은 방식으로 test합니다.

class Mathx{
    static boolean even(int integer){
        return integer % 2 == 0;
    }

    static boolean odd(int integer){
        return integer % 2 == 1;
    }
}

class MathxTest{
    public static void main(String[] args) {
        int even = (int)(Math.random() * 1000);
        int odd = (int)(Math.random() * 1000);

        System.out.format("is %d odd ? : %b %n", odd, Mathx.odd(odd));
        System.out.format("is %d even ? : %b %n", even, Mathx.even(even));


    }
}

kinetic energy

질량 , 속력인 물체의 운동에너지는 입니다.
운동에너지를 구하는 method는 Physics.kineticEnergy 입니다.
두 자동차의 질량과 속력를 받아 첫 자동차의 운동에너지가 두 번째보다 크면 true 아니면 false를 찍는 application을 짭니다. 모든 수는 double type입니다.

class Physics{
    static double kineticEnergy(double mass, double velocity){
        return 1/2d * mass * velocity * velocity;
    }
}

class PhysicsTest{
    public static void main(String[] args) {
        double firstMass = 200;
        double firstVelocity = 120;

        double secondMass = 150;
        double secondVelocity = 180;

        System.out.format("First Car, Mass : %f, Velocity : %f %n", firstMass, firstVelocity);
        System.out.format("Second Car, Mass : %f, Velocity : %f %n", secondMass, secondVelocity);

        double firstKinetic = Physics.kineticEnergy(firstMass, firstVelocity);
        double secondKinetic = Physics.kineticEnergy(secondMass, secondVelocity);

        System.out.format("Is First Car's Kinetic Energy bigger than Second's one ? : %b %n", firstKinetic > secondKinetic);
    }
}
profile
기록

1개의 댓글

comment-user-thumbnail
2023년 7월 21일

자바 언어의 Boolean Expressions에 대해 정말 잘 설명해주셔서 이해하는데 도움이 되었습니다. 특히, predicate logic에 대한 설명이나 각각의 연산자 사용법, 그리고 실제 적용 예제들이 매우 유익하게 느껴졌습니다. 계속해서 좋은 정보 공유 부탁드립니다. 감사합니다!

답글 달기