2014-10-31 266 views
-1

當我在沒有goto命令的情況下執行代碼時,它可以工作,但是當我添加:Start時,它會得到一個8錯誤。goto命令不起作用

下面是相關代碼:

 :Start 
     Console.Write("Do you want the yes or no?"); 
     string what = Console.ReadLine(); 
     switch (what) 
     { 
      case "yes": 
       Console.WriteLine("You choose yes"); 
       break; 
      case "no": 
       Console.WriteLine("You choose no"); 
       break; 
      default: 
       Console.WriteLine("{0},is not a word",what); 
       goto Start; 
     } 
+0

轉到哪種語言? – 2014-10-31 15:12:47

+4

正確的標籤語法:'開始:' – 2014-10-31 15:14:44

+1

請不要太習慣goto語句:https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF:D – SlySherZ 2014-10-31 15:15:58

回答

1

正確的語法是Start:。但是,不是goto,你應該在一個循環中進行設置:

bool invalid = true; 
while (invalid) 
{ 
    Console.Write("Do you want the yes or no?"); 
    string what = Console.ReadLine(); 
    switch (what) 
    { 
     case "yes": 
      Console.WriteLine("You choose yes"); 
      invalid = false; 
      break; 
     case "no": 
      Console.WriteLine("You choose no"); 
      invalid = false; 
      break; 
     default: 
      Console.WriteLine("{0},is not a word",what); 
    } 
} 
+2

'while(invalid)'看起來更符合邏輯 – 2014-10-31 15:18:13

+0

@AlexK。是的,我同意。 – 2014-10-31 15:23:51

0

試試 「開始:」 而不是 「:啓動」 這樣的:

Start: 
      Console.Write("Do you want the yes or no?"); 
      string what = Console.ReadLine(); 
      switch (what) 
      { 
       case "yes": 
        Console.WriteLine("You choose yes"); 
        break; 
       case "no": 
        Console.WriteLine("You choose no"); 
        break; 
       default: 
        Console.WriteLine("{0},is not a word", what); 
        goto Start; 
      } 

http://msdn.microsoft.com/en-us/library/aa664740(v=vs.71).aspx

0

一個標籤的正確的語法是Start:,不:Start

您可以重構代碼省略goto語句代替(better ):

bool continue = true; 
while (continue) { 
    Console.Write("Do you want the yes or no?"); 
    string what = Console.ReadLine(); 
    switch (what) 
    { 
     case "yes": 
      Console.WriteLine("You choose yes"); 
      continue = false; 
      break; 
     case "no": 
      Console.WriteLine("You choose no"); 
      continue = false; 
      break; 
     default: 
      Console.WriteLine("{0}, is not a word",what); 
      break; 
    } 
}