아핫뉴스실시간 인기검색어
아핫뉴스 화산 이미지
아하

생활

생활꿀팁

어린알파카245
어린알파카245

c# 랜덤하게 switch문의 case를 실행하는 방법

c# 랜덤하게 switch문의 case를 실행하는 방법이 있나요? 막연하게는 그냥 랜덤 함수를 생성하면 될 거 같은데.... 막상 해 보려니 잘 안 되네요ㅠ 알려주시면 감사드리겠습니다!

    55글자 더 채워주세요.
    2개의 답변이 있어요!
    • 즐거운다향제비
      즐거운다향제비

      랜덤함수를 통하여 랜덤한 수를 받아서 값을 처리한 뒤에 변수에 저장해서 그 변수값으로 switch문의 case 조건에 맞도록 하여 랜덤하게 실행하면 되지 않을까 싶습니다.

      그 외에도 자료구조에서 큐 등을 이용하는 방법도 있다고 하지만 난이도가 있는 관계로 랜덤함수 값을 처리하여 하는 것이 쉬을 것이라 생각됩니다.

    • [소스코드]

      using System;

      //참고1 : https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/switch

      public enum Color { Red, Green, Blue}

      namespace ConsoleApplication1

      {

      class Program

      {

      // 참고2 : https://crynut84.tistory.com/15

      static Random r = new Random();

      static void RandomEx()

      {

      Color c = (Color)(r.Next(0, 4));

      switch (c)

      {

      case Color.Red:

      Console.WriteLine("The color is red.");

      break;

      case Color.Green:

      Console.WriteLine("The color is green.");

      break;

      case Color.Blue:

      Console.WriteLine("The color is blue.");

      break;

      default:

      Console.WriteLine("The color is unknown.");

      break;

      }

      }

      static void Main(string[] args)

      {

      for (int i = 0; i < 10; i++)

      RandomEx();

      Console.ReadKey(); // 아무키나 입력하면 프로그램 종료!

      }

      }

      }

      [실행결과 캡쳐]