我是 C# 的新手,不知道如何在我已经编写的代码中进行验证。我的代码工作完美,但想继续添加功能。我正在寻找提示或任何您想提及的内容。提前致谢。 这是我目前拥有的代码,需要对绿色注释附近的 3 个 getInputs 进行验证。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BasicUserInterface
{
class Program
{
static void DisplayApplicationInformation()
{
Console.WriteLine("Welcome to the Basic User Interface Program");
Console.WriteLine("CIS247, Week 2 Lab");
Console.WriteLine("Name: Fred Ziyad");
Console.WriteLine();
Console.WriteLine("This program accepts user input as a string, then makes the");
Console.WriteLine("approppriate data conversion and display the results.");
Console.WriteLine();
}
static void DisplayDivider(String outputTitle)
{
Console.WriteLine("************* " + outputTitle + " **************");
}
static string GetInput(string inputType)
{
string strInput;
Console.Write("Enter " + inputType + ": ");
strInput = Console.ReadLine();
return strInput;
}
static void TerminateApplication()
{
Console.WriteLine();
Console.WriteLine("Thank you for using the Basic User Interface program");
Console.Read();
}
static void Main(string[] args)
{
int age;
double mileage;
string strInput, name;
DisplayApplicationInformation();
DisplayDivider("Start Program");
Console.WriteLine();
DisplayDivider("Get Name");
name = GetInput("your name");
Console.WriteLine("Your name is " + name);
Console.WriteLine();
//Validate name to be a string of letters.
DisplayDivider("Get Age");
strInput = GetInput("your age");
age = int.Parse(strInput);
Console.WriteLine("Your age is: " + age);
Console.WriteLine();
//Validate age to be a number.
DisplayDivider("Get Mileage");
strInput = GetInput("gas mileage");
mileage = double.Parse(strInput);
Console.WriteLine("Your car MPT is: " + mileage);
//Validate mileage to be a number.
TerminateApplication();
}
}
}
请您参考如下方法:
数字类型有一个 TryParse 方法,您可以使用它来捕获非法输入。
例子:
DisplayDivider("Get Age");
strInput = GetInput("your age");
if (int.TryParse(strInput, out age)) {
Console.WriteLine("Your age is: " + age);
Console.WriteLine();
} else {
Console.WriteLine("Age input was not a valid number.");
}
