我正在研究一个基本的控制台程序,如下所示。我很生气,后一段代码不起作用。检查用户输入年龄并从Console.WriteLine重新运行代码的最佳方法是什么(“好的。现在请输入您的年龄。”);到if语句。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Thank you for participating in this survey. Please take a moment to fill out the required information.");
Console.WriteLine("Please Type Your Name");
string name = Console.ReadLine();
Console.WriteLine("Okay. Now please enter your age.");
string age = Console.ReadLine();
Console.WriteLine("Your information has been submitted.");
Console.WriteLine("Name: " + name + "\n" + "Age: " + age);
Console.ReadLine();
int newAge = Int32.Parse(age);
if (newAge => 18)
{
}
}
}
}
答案 0 :(得分:0)
替换它:
int newAge = Int32.Parse(age);
用这个
int newAge = Convert.ToInt32(age);
。 如果你想更好地编码,请使用try-catch
try
{
int newAge = Convert.ToInt32(age);
}
catch(FormatException)
{
//do something
}
答案 1 :(得分:0)
您还可以使用TryParse,它为您执行错误测试,并将解析后的值作为out参数返回。当TryParse返回bool值时,您可以轻松检查转换是否有效。
string age = null;
int ageValue = 0;
bool succeeded = false;
while (!succeeded)
{
Console.WriteLine("Okay, now input your age:");
age = Console.ReadLine();
succeeded = int.TryParse(age, out ageValue);
}
你还可以将它反转为......而
string age = null;
int ageValue = 0;
do
{
Console.WriteLine("Okay, now input your age:");
age = Console.ReadLine();
} while (!int.TryParse(age, out ageValue));