FormatException C#

时间:2016-04-27 12:54:05

标签: c#

所以我目前正在学习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
            }
        }
    }
}
}

所以我试图说出&#34;这不是有效的输入&#34;键入字符串而不是整数时。

提前致谢! <3

3 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:1)

您应该使用int.TryParse来代替Parse,因为它具有内部异常处理机制,并且您可以使用它的返回值(true / false)来检查操作是否成功,转换成功后,它将返回true,失败转换的返回值将为false

int minutes;

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

答案 2 :(得分: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
}