[英]Validation of numbers and letters using C# for a beginner
我是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,如果字符串無法成功解析出一個有效的整數,並且,如果它成功的解析,將在輸出參數返回轉換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
為零
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.