[英]C# Parse string integer error?
我剛開始使用C#。今天,我正在嘗試編寫一個非常簡單的應用程序。 但是,當我使用console.readkey時,如果輸入的不是數字,則立即崩潰。
我完全理解它嘗試解析數字並將其轉換為字符串,但是,如果有人不插入數字,如何防止應用程序崩潰或失敗。 我在Google周圍搜索,但顯然這是很具體的事情。
我要做的就是將所有非數字的內容無效或解析出來,以免使應用程序感到困惑和關閉。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.Write("what is your age?");
string agestring = Console.ReadLine();
int age = Int32.Parse(agestring);
if (age >= 21)
{
Console.WriteLine("congrats, you're you can get drunk!");
}
else if (age < 21)
{
Console.WriteLine("Sorrrrrryyyyyyy =(");
}
else
{
Console.WriteLine("Sorry Thats not a valid input");
}
}
}
試試這個:
int age;
if(Int32.TryParse(agestring, out age))
{
if (age >= 21)
{
Console.WriteLine("congrats, you're you can get drunk!");
}
else
{
Console.WriteLine("Sorrrrrryyyyyyy =(");
}
}
else
{
Console.WriteLine("Sorry Thats not a valid input");
}
使用Int32.TryParse
方法,您可以檢查輸入的解析是否成功。 如果不是,則將消息打印到控制台。
您可以使用Int32.TryParse
方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.Write("what is your age?");
string agestring = Console.ReadLine();
int age;
if (Int32.TryParse(agestring, out age))
{
if (age >= 21)
{
Console.WriteLine("congrats, you're you can get drunk!");
}
else if (age < 21)
{
Console.WriteLine("Sorrrrrryyyyyyy =(");
}
}
else
{
Console.WriteLine("Sorry Thats not a valid input");
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.