if ( floure >= 4 && sugar >= 2 )
---------------- ---------------
밀가루 측정 설탕 측정
각 영역은 관계 (relational) 표현식이다. 관계 연산자는 주어진 식이 ture인지 false인지를 평가한다. 그후 boolean 연산자 &&로 두 관계 연산자의 평가 값을 평가한다. 이러한 평가식은 인간의 언어로 비슷하게 표현할 수도 있다. 위의 평가식을 인간의 언어로 풀어쓰면 밀가루가 4컵 이상이고 설탕이 2컵 이상이면 쿠키를 만들 수 있다정도가 될 것이다.
문제
flour이 9이고 sugar이 1이라면, 다음 표현식의 결과는 ?
flour >=4 True 혹은 False ?
sugar >=2 True 혹은 False ?
&&
관계 표현식에 대한 평가는 끝났다. 그럼 프로그램의 다음으로 넘어가 보자.
// check that there is enough of both ingredients
if ( flour >= 4 && sugar >= 2 )
System.out.println("Enough for cookies!" );
else
System.out.println("sorry...." );
당신은 위 프로그램의 결과를 예측할 충분한 정보를 가지고 있다. flour과 sugar의 값을 알고 있으며, 맛있는 쿠키를 만들기 위한 각각의 조건도 알고 있다. 맛있는 쿠기를 만들기 위한 조건은 다음과 같다.
flour >=4
and
sugar >=2
두 관계 연산 평가결과가 모두 true인지만 확인하면 된다. 그러면 "Enough for cookies!"메시지를 받을 수 있을 것이다.
여기에서 and에 해당 하는 것이 &&로 논리 연산자라고 부른다. 논리 연산자는 두개의 true|false값을 받은 다음 이것을 측정해서 하나의 true|false값을 반환한다.
AND 연산자
AND 연산자는 양쪽의 평가 값이 모두 true가 되어야 한다. 만약 양쪽 평가 값이 모두가 true라면, 이 식에 대해서 true가 평가된다. 어느 한쪽이라도 false가 있다면, 평가 값은 false가 된다.
https://docs.google.com/drawings/edit?id=1Gmp_2fUufs1mozy0ABec4kG-oO_2vkqG85NcBiCjpC8&hl=ko
여기에서 양쪽의 값에 따른 && 연산의 평가는 다음과 같다.
true
&&
true
=
true
false
&&
true
=
false
true
&&
false
=
false
false
&&
false
=
false
문제
다음과 같은 논리연산 표현식이 있다.
flour >= 4 && sugar >= 2
만약 flour이 2 그리고 sugar이 0이 주어지면 평가값은 어떻게 될까 ?
다음과 같이 표현식을 평가할 수 있을 것이다.
위의 문제에서 우리가 flour >= 2가 false인 것을 확인 했다면, 다음 주건인 sugar >= 2는 굳이 평가할 필요도 없다. sugar 이 참이건 거짓이건 결과는 무조건 거짓이라는 걸 알 수 잇기 때문이다.
flour >= 4 && sugar >= 2
------------ ------------
false && dos not matter
--------------------
false
그러므로 프로그래머는 굳이 두 번의 비교 연산을 할 필요 없이, 한번의 연산으로 그 결과를 확인하도록 프로그램을 최적화할 수도 있다. 두번 비교하는 것 보다 한번 비교하면 프로그램이 빨리 돌아갈 것임은 명백하다. 이에 대한 주제는 나중에 살펴보도록 할 것이다.
다음은 완전한 cookie 프로그램이다.
// Cookie Ingredients Checker
//
import java.util.Scanner;
class CookieChecker
{
public static void main (String[] args)
{
// Declare a Scanner and two integer variables
Scanner scan = new Scanner( System.in );
int sugar, flour;
// get the number of cups of flour
System.out.println("How much flour do you have?");
flour = scan.nextInt();
// get the number of cups of sugar
System.out.println("How much sugar do you have?");
sugar = scan.nextInt();
// check that there are enough of both ingredients
if ( flour >= 4 && sugar >= 2 )
System.out.println("Enough for cookies!" );
else
System.out.println("sorry...." );
}
}
다양한 방식으로 프로그램을 테스트 하면서, && 연산자를 확실히 이해하도록 하자.
자동차 대여 프로그램
당신은 자동차 대여 관련 업무를 보고 있다. 자동차를 대여하기 위해서는 다음과 같은 조건을 만족해야 한다.
21살 이상이 되어야 대여할 수 있다.
임차인은 반드시 10,000불 이상 사용가능한 신용 카드가 있어야 한다.
이 프로그램은 다음과 같다. 쿠키 프로그램과 매우 비슷해 보인다.
// Rental Car Checker
//
import java.util.Scanner;
class RenterChecker
{
public static void main (String[] args)
{
// Declare a Scanner and two integer variables
Scanner scan = new Scanner( System.in );
int age, credit;
// get the age of the renter
System.out.println("How old are you?");
age = scan.nextInt() ;
// get the credit line
System.out.println("How much credit do you have?");
credit = scan.nextInt() ;
// check that both qualifications are met
if ( _________________ && __________________ )
System.out.println("Enough to rent this car!" );
else
System.out.println("Have you considered a bicycle?" );
}
}
문제
밑줄을 채워서 완전한 프로그램으로 만들어라.
if (age >= 21 && credit >= 10000)
고객은 양쪽 조건을 모두 만족시켜야만 한다. 모두 만족시켜야 하므로 &&연산자를 이용해서 양쪽 모두가 true인지를 평가하고 있다.
복싱선수는 체급에 맞는 몸무게를 유지해야 한다. 웰터급 선수의 경우 136 에서 147 파운드 사이의 몸무게를 유지해야만, 시합을 할 수 있다. 여기 복싱선수의 몸무게를 측정하는 프로그램이 있다. 이 프로그램은 복싱선수의 몸무게를 입력받아서, 시합을 할 수 있는지를 검사한다.
// Ringside Weigh-in
//
// Boxer must weigh between 136 and 147 pounds
//
import java.util.Scanner;
class Ringside
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int weight;
// get the weight
System.out.print("How heavy is the boxer? ");
weight = scan.nextInt();
// check that the weight is within range
if ( )
System.out.println("In range!" );
else
System.out.println("Out of range." );
}
}
문제
&&
AND 연산자
문제
쿠키 프로그램
자동차 대여 프로그램
문제
다양한 고객을 측정하기
범위 측정 하기
Recent Posts
Archive Posts
Tags