2014-12-27 61 views
1

在我的代碼:如何讓程序返回Console.Writeline(「ERROR INVALID INPUT」)而不是給我一個例外?

{ 
    int coffecost = 0; 
    string coffesize = null; 
    Console.WriteLine("1. Small 2. Medium 3. Large"); 
    Console.WriteLine("Choose your coffe please but enter your name first!"); 
    string name = Console.ReadLine(); 
    Console.WriteLine("So your name is {0}! What coffe would you like?", name); 
    int coffetype = int.Parse(Console.ReadLine()); 

    switch (coffetype) 
    { 
     case 1: 
      coffecost += 1; 
      coffesize = "small"; 
      break; 
     case 2: 
      coffecost += 2; 
      coffesize = "medium"; 
      break; 
     case 3: 
      coffecost += 3; 
      coffesize = "Large"; 
      break; 
     default: 
      Console.WriteLine("{0} is an invalid choice please choose from one of the 3!", coffetype); 
      break; 
    } 

    Console.WriteLine("Receipt: \n Name: {0} \n Coffee type: {1} \n Coffee cost: {2} \n Coffee size: {3}", name, coffetype, coffecost, coffesize); 
} 

這個簡單的程序生成收據從咖啡的類型。現在在我的程序中,您將1,2或3指定爲小,中,大。但是,如果你輸入一個無效字符說「,」,那麼你會收到一個異常,程序將崩潰。我想讓程序返回「這不是一種咖啡!」我怎麼能這樣做,而不是崩潰。另外對於練習,我計劃添加一個功能,您可以添加諸如奶油,糖或人造甜味劑等配料。現在我希望能夠將所有這些成分放在同一行,並將它們讀出來。例如,我加入了奶油,糖,人造甜味劑,它說你放進去了(它會讀出成分)但是如果我不說糖,我希望它只是印刷「你選擇了奶油和人造甜味劑!所有幫助表示讚賞:d

回答

1

簡單地改變

int coffetype = int.Parse(Console.ReadLine()); 

int coffetype = 0; 

if (!int.TryParse(Console.ReadLine(), out coffetype)) { 
    Console.Writeline(「ERROR INVALID INPUT」); 
    return; 
} 
+0

你介意給我解釋一下!這是int.tryparse之前? – 2014-12-27 19:58:36

+0

當然@MattJones,!是布爾表達式的否定運算符,如果您查看http://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx上的TryParse簽名,您將看到此方法返回如果它可以解析提供的字符串,否則爲真,所以在這種情況下,只有在TryParse無法解析字符串值 – Victor 2014-12-27 20:05:18

+0

時,我們需要編寫「錯誤無效輸入」,因此基本上它使得我不必將bool = int .tryparse(輸入,輸出); – 2015-01-02 02:40:00

0

您使用Int32.TryParse

int coffetype; 
string input = Console.ReadLine(); 
if(!Int32.TryParse(input, out coffetype)) 
    Console.WriteLine(coffeType.ToString() + " IS AN INVALID INPUT"); 
else 
{ 
    ..... 
} 

該方法嘗試輸入字符串轉換成整數,但是,在錯誤的情況下,它不會拋出異常,只是返回false離開變量coffetype至0

在其默認值的您也可以避免測試,並讓交換機中的默認情況處理無效輸入。

int coffetype; 
string input = Console.ReadLine(); 

// Not really need to test if Int32.TryParse return false, 
// The default case in the following switch will handle the 
// default value for coffetype (that's zero) 
Int32.TryParse(input, out coffetype); 
switch (coffetype) 
{ 
    case 1: 
     ..... 
    default: 
     Console.WriteLine("{0} is an invalid choice please choose from one of the 3!", coffetype); 
     break; 
} 
相關問題