2016-04-27 68 views
1

所以我目前正在參加C#編程課程,以獲得更新。FormatException C#

原來我忘了一些重要的事情!

namespace FitnessFrog 
{ 
class Program 
{ 
    static void Main() 
    { 
     int runningTotal = 0; 

     bool keepGoing = true; 

     while(keepGoing) 
     { 

      // Prompt the user for minutes exercised 
      Console.Write("Enter how many minutes you exercised or type \"quit\" to exit: "); 
      string input = Console.ReadLine(); 

      if (input == "quit") 
      { 
       keepGoing = false; 
      } 
      else 
      { 
       try 
       { 
        int minutes = int.Parse(input); 
        runningTotal = runningTotal + minutes; 

        if(minutes <= 0) 
        { 
         Console.WriteLine("Eh, what about actually exercising then?"); 
         continue; 
        } 
        else if(minutes <= 10) 
        { 
         Console.WriteLine("Better than nothing, am I right?"); 
        } 
        else if (minutes <= 24) 
        { 
         Console.WriteLine("Well done, keep working!"); 
        } 
        else if (minutes <= 60) 
        { 
         Console.WriteLine("An hour, awesome! Take a break, ok?"); 
        } 
        else if (minutes <= 80) 
        { 
         Console.WriteLine("Woah, remember to drink if you're going to exercise THAT long!"); 
        } 
        else 
        { 
         Console.WriteLine("Okay, now you're just showing off!"); 
        } 
        Console.WriteLine("You've exercised for " + runningTotal + " minutes"); 
       } 
        catch(FormatException) 
        { 
         Console.WriteLine("That is not valid input"); 
         continue; 
        } 




       // Repeat until the user quits 
      } 
     } 
    } 
} 
} 

所以我試圖讓它說「這不是有效的輸入」,當你鍵入一個字符串,而不是一個整數。

在此先感謝! <3

+0

所以...什麼問題? – raidensan

回答

1

您應該使用int.TryParse代替瞭解析,由於具有內部的異常處理機制的話,你可以用它的返回值(true/false)來檢查操作是否成功,對於成功的轉換它將返回true,並且故障轉換的返回值將是false

int minutes; 

if(!int.TryParse(input,out minutes) 
{ 
    Console.WriteLine("invalid input"); 
} 
else 
{ 
    // Proceed 
} 
2

int minutes = int.Parse(input); - 你應該使用的TryParse()代替Parse()

int minutes; 
bool parsed = int.TryParse(input, out minutes); 
if (parsed) 
{ 
    // your if statements 
} 
else 
{ 
    Console.WriteLine("That is not valid input"); 
} 
+0

哦,好吧。我會嘗試,謝謝。 '<3' – MibMoot

0

如果您收到來自用戶的輸入,你將要實際考慮使用Int32.TryParse()方法,以確定是否解析成功與否:

int minutes; 
// Attempt the parse here 
if(Int32.TryParse(input, out minutes)) 
{ 
    // The parse was successful, your value is stored in minutes 
} 
else 
{ 
    // The parse was unsuccessful, consider re-prompting the user 
} 
相關問題