Unity 기본3 - C#의 if와 switch 제어문

제어문은 상황에 따라 명령어의 실행을 선택하고 순서를 바꾸거나 반복시키는 명령

 

1. if문 기본1

 

if (조건식)

{

  조건이 참이면 실행시킬 명령

}

 

if 다음 조건식은 괄호로 둘러싸주고

 

{} 내에 여러 문장 사용 가능하고,

 

실행시킬 명령이 단 1문장이면 {}는 생략가능하나, 웬만하면 쓰는게 좋다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int age = 18;

        if (age < 20)
        {
            Debug.Log("애기");
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

중괄호 안에 들여쓰기(tab)은 생략가능하다.

 

중괄호 안에 넣기만 하면 되는데

 

보기 좋게할려면 들여쓰기 쓰는게 좋다

 

 

 

 

 

 

2. if else문

 

조건식이 참이 아닐 때도 무언가 실행시키고 싶다

 

if (조건식)

{

   조건식이 참이면 실행시킬 명령

}

else{  조건식이 거짓이면 실행시킬 명령}

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int age = 28;

        if (age < 20)
        {
            Debug.Log("애기");
        }
        else
        {
            Debug.Log("아재");
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

3. if else if else문

 

if (조건식1)

{

 조건식 1이 참이면 실행

}

else if (조건식2)

{

 조건식 1이 거짓이고, 조건식2가 참이면 실행

}

else

{

조건식1,2가 모두 거짓이면 실행

}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int age = 28;

        if (age < 20)
        {
            Debug.Log("애기");
        }
        else if (age < 30)
        {
            Debug.Log("애송이");
        }
        else 
        {
            Debug.Log("아재");
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

당연히 조건문은 계속해서 추가할 수 있다

 

if 

else if

else if

else if

...

else

 

-----------------------------------------------------------

 

알고 있겠지만, 조건문이 여러개인 경우 조건식을 잘 써야한다

 

위에서부터 아래로 실행되기 때문에

 

age = 18

 

if (age < 30){

A

}

 

else if (age < 20) {

B

}

 

....

 

이렇게 쓴다면?

 

age = 18 < 20이므로 의도는 B가 실행되길 원하는데

 

age 18 < 30이므로 A가 실행되고 B는 실행되지 않는다.

 

 

4. switch문

 

switch (A){

case B:

(C)

break;

case D:

(E)

break;

...}

 

A와 B가 같으면 C를 실행하고, break를 만나면 switch를 탈출

 

A와 B가 다르면 다음 case로 넘어가고 A와 D가 같으면 E를 실행하고 break를 만나면 switch를 탈출

 

case 옆에는 세미콜론이 아니고 콜론 :을 붙인다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        string groupName = "르세라핌";

        switch (groupName)
        {
            case "르세라핌":
                Debug.Log("르세라핌? 멤버들이 매력적이야!");
                break;
            case "뉴진스":
                Debug.Log("뉴진스는 노래가 좋아");
                break;
            case "카라":
                Debug.Log("이번에 컴백했잖아! 우주를 지배할 아이돌!");
                break;

        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

참고로 C#에서는 case와 case 사이에 break를 반드시 써야함

 

 

 

 

특수한 경우 break 생략가능한데, case를 연달아 쓰는 경우

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        string groupName = "르세라핌";

        switch (groupName)
        {
            case "르세라핌":
            case "뉴진스":
                Debug.Log("뉴진스는 노래가 좋아");
                break;
            case "카라":
                Debug.Log("이번에 컴백했잖아! 우주를 지배할 아이돌!");
                break;

        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

case A:

case B:

 (C)

break;

 

이렇게 case를 연달아 쓰는 경우는 가능하다.

 

위 경우 groupName이 "르세라핌"이 맞거나 "뉴진스"가 맞거나 둘중 하나라도 맞으면  "뉴진스는 노래가 너무 좋아"

 

A나 B중 하나라도 맞으면 (C)를 실행

 

 

 

 

당연하지만 모든 case에 해당되지 않는 경우, 아무것도 출력되지 않는다

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        string groupName = "트와이스";

        switch (groupName)
        {
            case "르세라핌":
                Debug.Log("르세라핌 멤버는 매력적이야");
                break;
            case "뉴진스":
                Debug.Log("뉴진스는 노래가 좋아");
                break;
            case "카라":
                Debug.Log("이번에 컴백했잖아! 우주를 지배할 아이돌!");
                break;

        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

모든 case를 다 체크할 수 없기 때문에... 어떠한 case에 걸리지 않는 경우 else문 같이

 

default:를 이용하면 어떠한 case에 걸리지 않는 경우 해당 case를 출력

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        string groupName = "트와이스";

        switch (groupName)
        {
            case "르세라핌":
                Debug.Log("르세라핌 멤버는 매력적이야");
                break;
            case "뉴진스":
                Debug.Log("뉴진스는 노래가 좋아");
                break;
            case "카라":
                Debug.Log("이번에 컴백했잖아! 우주를 지배할 아이돌!");
                break;
            default:
                Debug.Log("누군지 잘 모르지만, 누군가는 좋아할거에요.");
                break;

        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

마지막으로 switch (값)에서 (값)에는 조건식이 들어가도 되고 어떤 변수든 들어가도 상관 없다

 

위 코드에서 (값)에는 문자열이 들어가있는데 C#이라 가능하다.

 

C에서는 숫자만 들어갈 수 있고 문자열은 바로 들어갈 수 없다고 한다

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int a = 3;
        int b = 4;

        switch (a == b)
        {
            case true:
                Debug.Log("르세라핌 멤버는 매력적이야");
                break;
            case false:
                Debug.Log("뉴진스는 노래가 좋아");
                break;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

5. 연습문제1

 

변수에 숫자를 넣고 양수인지 음수인지 0인지 출력하는 프로그램

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int a = 3;
        
        if (a > 0)
        {
            Debug.Log("a는 양수입니다.");
        }
        else if (a < 0)
        {
            Debug.Log("a는 음수입니다.");
        }
        else
        {
            Debug.Log("a는 0입니다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

6. 연습문제2

 

주어진 연도가 윤년인지 구별하는 프로그램

 

4로 나누어떨어지면 윤년

 

4로 나누어떨어지더라도, 100으로 나누어 떨어지면 평년

 

4로 나누어떨어지고 100으로 나누어 떨어지더라도, 400으로 나누어 떨어지면 윤년

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        int year = 1994;

        if (year % 4 == 0)
        {
            if (year % 100 == 0)
            {
                if (year % 400 == 0)
                {
                    Debug.Log("윤년입니다.");
                }
                else
                {
                    Debug.Log("평년입니다.");
                }
            }
            else
            {
                Debug.Log("윤년입니다.");
            }
        }
        else
        {
            Debug.Log("평년입니다.");
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

7. 연습문제3

 

문자열 변수에 연산자 +,-,*,/ 중 하나를 넣고, 두 숫자 변수에 숫자를 넣고

 

문자열 변수 값에 따라 연산 결과를 출력

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

        string op = "*";

        int a = 3;
        int b = 4;

        switch (op)
        {
            case "+":
                Debug.Log(a + b);
                break;
            case "-":
                Debug.Log(a - b);
                break;
            case "*":
                Debug.Log(a * b);
                break;
            case "/":
                Debug.Log(a / b);
                break;
        }

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

TAGS.

Comments