[英]FormatException 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
}
}
}
}
}
因此,當您鍵入字符串而不是整數時,我試圖讓它說“這是無效的輸入”。
提前致謝! <3
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");
}
您應該使用int.TryParse
代替Parse,因為它具有內部異常處理機制,並且您可以使用它的返回值(true / false)來檢查操作是否成功,為了成功轉換它將返回true,並且失敗轉換的返回值將為false
int minutes;
if(!int.TryParse(input,out minutes)
{
Console.WriteLine("invalid input");
}
else
{
// Proceed
}
如果您正在接收來自用戶的輸入,您將需要考慮實際使用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.