2011년 4월 26일 화요일

자바의 제어문(if)

오늘부터는 자바의 제어문(Control Flow Statement)에 대해서 알아보기로 하겠다. 제어문이란 말 그대로 프로그램의 흐름을 제어하는 역활을 담당한다. 대표적인 제어문으로 조건을 나타내는 if나 switch, 반복을 나타내는 for나 while, 그리고 예외처리를 할수있는 try나 catch를 통해 프로그램을 여러분의 입맛대로 마음껏 요리할수 있게 될것이다.


이번 시간에는 조건을 나타내는 if문에 대해서 알아보기로 하겠다. 영어에서 풍기듯 만약 여러분이 제시한 조건을 만족할경우 설정해놓은 명령대로 처리하게 만들수 있는 것이 if의 주된 요지이다. 자바코드는 다음과 같이 이루어진다.

if (조건)
{
명령문1;
명령문2;
명령문3;
......
}

즉 조건이 true가 성립되면 중괄호 블록안의 명령문들이 차례대로 실행된다. 모든 제어문에서 { }는 안에 명령문이 한줄일 경우 생략이 가능하나 두줄 이상일 경우에는 중괄호로 묶어주어야 한다. 그럼 직접적인 예제를 통해서 if문을 살펴보겠다.


조건문에서 a가 10과 같으면 a와 b를 더하라는 프로그램이다. a가 10이니 더한값 30을 출력한다. 그럼 다음 예제를 살펴보자.


if문이 일단 두개가 있다. 첫번째 if문에서 조건을 검색한후에 참이면 안에 내용을 실행하고 아니면 다음 if문으로 넘어간다. 두번째 if문에서는 total이 20보다 작아야 참이 되므로 첫번째 if문에서 거짓이 나와 첫번째 명령문들이 실행되지 않아야 두번째 if문이 수행될수 있다. 프로그램을 짜고 결과를 생각해보고 자바를 실행해보기 바란다. 덧붙여 설명하자면 a가 10이고 b가 20이다. a가 10보다 크거나 같은지를 물으므로 true이고 b가 20보다 작거나 같은지를 물으므로 역시 true이다. 따라서 안의 명령문 두줄을 처리한다. 다음 total이 20보다 작냐고 물었는데 앞의 if문을 처리했으니 total값이 0이 아니라 현재 30이다. 따라서 두번째 if문은 처리되지 않는다. 그런데 이상하지 않나? 실행해보면 두번째 if문이 그것도 두번째줄이 처리된 것을 볼수 있다. 희한하다. 왜일까? 그렇다. 두번째 if문의 명령문은 첫째줄만 해당하지 둘째줄은 if문과 상관없이 프로그램을 실행하면 항상 처리된다. 이유는 { }. 아까 중괄호가 없는 제어문은 한줄만 명령문으로 인식한다 하였다. 까먹은 이들은 반성하자. -.- 이번에는 if else 구문을 공부해 보겠다.

if (조건)
{
명령문1;
...
}
else
{
명령문2;
...
}

즉 조건을 만족하면 명령문1을 실행하고 조건을 만족하지 못하면 명령문1 대신에 명령문2를 실행한다. 한마디로 양자택일이라 할수 있겠다. 다음 예제를 통해 if else 구문을 살펴보기로 하자.


위의 예제는 if문과 else문을 함께 적어놓은 것이다. 프로그램에 대해서 설명하자면 지금 지원자가 음대에 지원을 했다. 다른 과목은 점수가 미달하더라도 음악 점수만 80점을 초과하면 들어갈수 있는 학교다. 근데 지원자가 놀라운 성적으로 음악 과목만 88점을 획득하였다. 따라서 합격했다는 기분좋은 스토리(?)다. ㅎㅎ if문이 참이다. 따라서 else문은 처리하지 않는다. 지원자를 가상히 여겨 기왕이면 다홍치마 합격하는 걸로 만들었다.^^ 이해하는데 무리가 없을걸로 생각하고 다음으로 넘어가겠다.

이번에는 else if 구문이다. 당연하지만 첫번째 조건문은 if로 시작해야된다. 이 조건문은 해당하는 케이스가 나올때까지 조건을 검색하는 제어문이다.

if (조건1)
{
명령1;
...
}
else if (조건2)
{
명령2;
...
}
else if (조건3)
{
명령3;
...
} //원할시 여기서 끝내는 것도 가능하다.
else
{
명령; //위의 케이스 모두 해당사항 없을시 실행된다.
...
}

한마디로 조건이 참이 될때까지 검색해 보는 것이다. 이런 else if 조건문은 여러분이 원하는만큼 만들수 있다. 예제를 통해 어떤 프로그램을 만들수 있는지 살펴보기로 하자.


필자가 오래간만에 긴 프로그램을 만드느라 무리(?)한만큼 여러분도 그에 상응하는 시간을 투자해 본인의 것으로 만들기 바란다. 프로그램을 설명하자면 a라는 게이머가 미로게임하다가 4차관문까지 통과하고 함정에 빠져 게임이 끝나버렸다. a게이머가 게임하면서 받은 스코어(85점)를 토대로 결과를 출력하는 프로그램이다. 해당되는 조건이 있을때까지 검색하다가 해당사항이 있으면 그 해당 명령문을 실행하고 제어문을 빠져나오는 프로그램이다. 특별히 어려운 점은 없으리라 보인다. a값을 변경해 가면서 모든 조건을 다 만족하는지 살펴보기 바란다. 위의 결과값은 4번째 조건문을 만족하므로 아래와 같다.

4차 관문까지 통과하셨습니다.
게임을 종료합니다.^^

질문 있나? 어디 똑똑한 학생 질문 없을까? 허걱~ 질문 있어야 하는데...^^ 이 프로그램에는 아주 치명적인 에러가 하나 있다. 무엇일까? 궁금하면 50점 아래로 a값을 넣고 자바를 돌려본다. 황당하지 않은가? 택도 없는 점수를 넣었는데도 여러분이 게임지존이라고 나올 것이다. 즉 if를 비롯 else if까지 체크한 4가지 조건문 모두 만족하는게 없으므로 else를 실행하게 되는 것이다. 반대로 4가지 조건문 중에 하나라도 만족하는게 있으면 else 구문은 실행되지 않는다. 마지막에 else 구문을 써도 되지만 꼭 그럴 필요는 없다. 이런 경우 else 구문 대신에 else if 구문을 한번 더 쓰고 끝내버리면 해결된다. 아래글을 읽기전에 해결방법을 각자 모색해보기 바란다.

몇가지 방법을 제시해 보겠다. 물론 50점 아래 범위를 관계연산자를 써서 다른 케이스와 같이 a>0 부터 a<=50 까지 조건문을 만들어서 쓸수도 있을테고 새로운 변수를 하나 더 써서 아주 간단하게 넘어갈수도 있다. 어차피 점수가 50점 아래일 경우 마지막 케이스만 실행되지 않게 만들면 되니까 변수를 하나 써서(int b=0;) 마지막 else 구문 대신에 else if (b!=0) 구문으로 고쳐서 돌릴수도 있을 것이다. 물론 후자보다는 전자의 경우가 명료하고 정확하므로 전자를 선택하는 것을 추천한다. 후자는 프로그램이 길어지면 길어질수록 오류가 날경우 문제를 해결하기가 힘들어진다. 여기서는 기계적인 오류가 아니라 논리적인 오류가 났을경우 여러 해결방법이 있다는 것을 보여주기 위해 예를 들어본 것이니 많은 응용을 통해 오늘 배운 if 조건문을 마스터하기 바란다.

마지막으로 새로운 if else 구문을 소개하겠다. if else 구문을 축약형으로 ?와 :(콜론)을 이용해서 한줄로 표시할수 있는데 예제를 보면 한번에 이해가 갈것이다.

if (a > b)
  result = a;
else
  result = b;

위의 구문을 한줄로 쓰는게 가능하다.^^ 어떻게? 요렇게~
result = (a > b) ? a : b;

물론 a, b, result 세개의 변수는 int형이라고 선언했다고 하고 위와 같이 단 한줄로 축약해서 쓰는 것이 가능하다. 공식화해서 쓴다면 아래와 같이 생각해볼수 있을 것이다.
리턴값 = (조건문) ? 값이 true일 경우 : 값이 false일 경우;

물론 마지막에는 콜론이 아닌 ;(세미콜론)이 들어가야 한다.
또한 else if처럼 조건문을 더 달수도 있다.
리턴값 = (조건문)? 값이 true일 경우 : (조건문)? : 값이 true일 경우 : 값이 false일 경우;

이 정도 설명했으면 이해되었을테니 본 강의는 여기서 마치겠다.^^

댓글 26개:

  1. Great article! This is the type of info that are meant to be shared across the net.
    Shame on Google for now not positioning this submit upper!
    Come on over and seek advice from my website
    . Thanks =)
    http://ow.ly/hozOz
    Also visit my weblog - kupiti youtube pogled

    답글삭제
  2. This page definitely has all of the info I wanted concerning this subject and didn't know who to ask.

    Here is my webpage; comprar y conseguir más seguidores en Twitter
    my website > comprar y conseguir más seguidores en Twitter

    답글삭제
  3. If some one wants to be updated with most recent technologies after that he must be go to see this site and
    be up to date all the time.

    My blog post: comprar seguidores en Instagram barato

    답글삭제
  4. It's nearly impossible to find knowledgeable people on this topic, but you seem like you know what you're talking about!
    Thanks
    http://pemasaraninternet.webs.com/apps/blog/show/23831378-how-to-pick-the-coolest-iphone-5-cases

    답글삭제
  5. This paragraph is actually a pleasant one it helps new web visitors, who are wishing for blogging.


    my blog post - comprar seguidores Instagram

    답글삭제
  6. Why viewers still make use of to read news papers when in this technological world everything
    is accessible on net?

    my web-site: iphone 5 casos

    답글삭제
  7. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make
    your point. You definitely know what youre talking about,
    why throw away your intelligence on just posting videos to your weblog when you
    could be giving us something informative to read?



    my web page: fauman

    답글삭제
  8. Very quickly this web page will be famous amid all blog users, due to it's fastidious articles
    http://ow.ly/hUkYP youtube likes

    Look into my blog post :: youtube views

    답글삭제
  9. Do you have a spam problem on this site; I also am a blogger,
    and I was wondering your situation; many of us have created some
    nice methods and we are looking to trade strategies with other folks, be sure to shoot me an email
    if interested.
    http://ow.ly/hUjMU apartments for rent in santa monica

    Look at my web-site; santa monica apartment

    답글삭제
  10. Excellent post. I will be dealing with a few of these issues as well.
    .
    " http://is.gd/BzE5gm increase youtube views reviews "

    my web-site youtube comments

    답글삭제
  11. always i used to read smaller articles or reviews which as well clear their motive, and that
    is also happening with this piece of writing which I am reading at this time.

    http://nicerdicer.ucoz.de/ genius nicer dicer plus reviews

    답글삭제
  12. Thanks for ones marvelous posting! I actually enjoyed reading it, you happen to be a great author.
    I will always bookmark your blog and may come back someday.
    I want to encourage you to continue your great job, have a nice holiday weekend!

    http://singaporetuitiontutoragency.webs.com/

    답글삭제
  13. if문 만큼 중요한 것도 없다고 생각하는데

    재미있게 잘 봤습니다

    앞으로도 쭉쭉 달리겠습니다!

    답글삭제
  14. 짧지만 재미있어서 쏙쏙 들어오네요.
    여기 짱짱!

    답글삭제
  15. When I originally left a comment I seem to have clicked on the
    -Notify me when new comments are added- checkbox and from now
    on each time a comment is added I receive four emails with the exact same comment.
    There has to be a way you are able to remove me from that service?
    Many thanks!

    Here is my web page - buying d3 gold

    답글삭제
  16. When I originally left a comment I seem to have clicked on the -Notify me when new
    comments are added- checkbox and from now on each time a comment
    is added I receive four emails with the exact same comment.
    There has to be a way you are able to remove me from
    that service? Many thanks!

    Visit my weblog buying d3 gold

    답글삭제
  17. In essence you will see the opportunities to create what
    you want all around you. Anyway, whole, clean foods are what your
    body needs, and plenty of them. This is because the less you weigh the
    fewer calories it takes to function.

    Feel free to visit my website - weigh loss

    답글삭제
  18. Your style is so unique compared to other people I have read stuff
    from. I appreciate you for posting when you have the opportunity, Guess I will just bookmark this page.


    Feel free to surf to my weblog :: mobile games

    답글삭제
  19. Hey there! I've been following your site for
    some time now and finally got the courage to go ahead and give you a shout
    out from Porter Tx! Just wanted to tell you keep up the fantastic
    work!

    Here is my web-site - 128x160 mobile games

    답글삭제
  20. Great goods from you, man. I have understand your stuff previous to and you're just too
    great. I really like what you've acquired here, certainly like what you're stating and the way in which
    you say it. You make it entertaining and you still care for to keep it sensible.
    I can not wait to read much more from you. This is really a wonderful website.


    My blog - hungry shark evolution cheats

    답글삭제
  21. Write more, thats all I have to say. Literally, it seems as
    though you relied on the video to make your point.

    You clearly know what youre talking about, why throw away your
    intelligence on just posting videos to your
    site when you could be giving us something informative to read?


    Also visit my webpage: 8 ball pool hack

    답글삭제
  22. I like the valuable information you provide in your articles.
    I'll bookmark your blog and check again here regularly.
    I'mquite certain I will learn plenty of new stuff right here!
    Best of luuck for the next!

    Here is my page ... wind energy facts for kids

    답글삭제
  23. I do believe all of the ideas you've offered for your post.

    They are really convincing and can definitely
    work. Nonetheless, the posts are very brief
    for newbies. May you please lengthen them a little from next
    time? Thanks for the post.

    My homepage: world of warplanes download

    답글삭제
  24. What's up to all, it's genuinely a fastidious for me to pay a quick visit this site, it contains important Information.

    my site: jetpack joyride cheats

    답글삭제
  25. The other day, while I was at work, my sister stole my apple ipad and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!


    Here is my weblog the sims freeplay cheats lp

    답글삭제
  26. It's enormous that you are getting thoughts from this
    piece of writing as well as from our discussion made here.



    Look at my webpage icon pop quiz cheats characters level 5

    답글삭제