2016-12-10 2 views
2

goto 문을 사용하고 싶지는 않지만 기본 대문자가 실행될 때 주 메뉴로 돌아가 길 원합니다. 방법?? 나는 이것이 단순한 문제라는 것을 알고 있지만 매우 비슷한 것을 경험하는 많은 초보자가 있어야합니다. 당신이 할 수 @ Abion47 옆에C#에서 goto 문 피하기

int Size = -1; 

while (Size == -1) { 
    Console.WriteLine("Pick a coffee Size"); 
    Console.WriteLine("1: Small"); 
    Console.WriteLine("2: Medium"); 
    Console.WriteLine("3: Large"); 
    Size = int.Parse(Console.ReadLine()); 
    switch (Size) 
    { 
     case 1: 
      price += 1.20; 
      break; 
     case 2: 
      price += 1.70; 
      break; 
     case 3: 
      price += 2.10; 
      break; 
     default: 
      Size = -1; 
      Console.WriteLine("This option does not exist"); 
      break; 
    } 
} 
+2

수행에게'할 {...} 동안 같은 것을 만들 것입니다. –

+0

기본 case 문에서'break' 대신'return'을 사용해 보았습니까? – ColinM

+0

switch 문이 끝난 직후에'if (price == 0) continue;를 추가 할 수 있습니다. 이것은 사람이 이미 커피를 구매 한 경우 작동하지 않는 루프 – KMoussa

답변

9

은 당신의 주석 라인을 교체 메뉴에 대한 기능과 스위치에 대한 기능도 작성하십시오. (! userInputValid)`

이 예제에서는 무한 루프 메뉴

static void Menu() 
{ 
    Console.WriteLine("Menu"); 
    Console.WriteLine("1) Take me to My fancy menu"); 
} 
static void SwitchFunc(string input) 
{ 
    switch (input) 
    { 
     case "1": 
      Menu(); 
      string inputB = Console.ReadLine(); 
      SwitchFunc(inputB); 
      break; 
    } 
} 



static void Main(string[] args) 
{ 
    Menu(); 
    string input = Console.ReadLine(); 
    SwitchFunc(input); 

} 
1

, 당신은 다음과 같은 뭔가이 작업을 수행 할 수 있습니다

static void buycoffee() 
{ 
    Double price = 0; 
    int x = 0; 
    while (x == 0) 
    { 
     Console.WriteLine("Pick a coffee Size"); 
     Console.WriteLine("1: Small"); 
     Console.WriteLine("2: Medium"); 
     Console.WriteLine("3: Large"); 
     int Size = int.Parse(Console.ReadLine()); 
     switch (Size) 
     { 
      case 1: 
       price += 1.20; 
       break; 
      case 2: 
       price += 1.70; 
       break; 
      case 3: 
       price += 2.10; 
       break; 
      default: 
       Console.WriteLine("This option does not exist"); 
       ///how to return to the main menu here 
       break; 
     } 
     Console.WriteLine("Would you like to buy more coffee?"); 
     String Response = Console.ReadLine().ToUpper(); 
     if (Response.StartsWith("Y")) 
     { 
      Console.Clear(); 
     } 
     else 
     { 
      x += 1; 
     } 
    } 
Console.WriteLine("The total bill comes to £{0}", price.ToString("0.00")); 
} 

} 
+0

기본 케이스의 중단은 스위치가 켜진 후에 추가 로직이 계속 발생할 수 있도록 허용해야합니다. 유효한 옵션의 경우. –

+0

@RobertHickman이 솔루션의 요점은 유효한 옵션의 경우 while 루프를 벗어나는 것입니다. 원래 코드에서와 같은 루프가 아닙니다. – Abion47

+0

확인. 그래서 OP는 "더 많은 커피"기능을 얻기 위해 루프를 다른 루프로 감쌀 필요가 있습니다. –

1

및 @Dogu 아르 슬란의 답변 : 니코 Schertier 말했듯이 continue;

+0

@EatPeanutButter. 꽤 괜찮은데. 내부 함수를 호출하면 메모리에 문제가 발생합니까? – Rich