初学者使用C#验证数字和字母
本文关键字:数字 验证 初学者 | 更新日期: 2023-09-27 18:20:14
我是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.");
}
//Validate age to be a number.
以下是验证字符串是否为数字的方法:
string str = "123";
int result;
if (!Int32.TryParse(str, out result))
; //not a whole number
如果字符串未成功解析为有效整数,则TryParse
将返回false;如果成功解析,则将在out参数中返回转换后的int。
或者,如果你想允许小数:
string str = "123.5";
double result;
if (!Double.TryParse(str, out result))
; //not a number
相同的想法
//Validate name to be a string of letters.
以下是如何计算字符串中而非字母的字符数:
string str = "AB3C";
int numberOfNonLetters = str.Count(c => !Char.IsLetter(c));
要确保字符串只有字母,只需确保numberOfNonLetters
为零即可。