我搜索了stackoverflow,但没有找到任何能回答我问题的内容。不幸的是,单词作为搜索查询并不是一个简单的问题。
我正在使用c#,我有一个菜单,要求用户从1 - 4中选择一个选项。我确认所选的值是一个整数,但每当我输入一个字母或符号时,我的代码就会中断。如何为此添加验证?我的代码目前如下。
static void Main(string[] args)
{
DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
FileInfo[] files = folderInfo.GetFiles();
int mainMenuChoice=0;
while ( mainMenuChoice != 1 || mainMenuChoice!= 2 || mainMenuChoice!= 3 || mainMenuChoice!= 4)
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Full File Listing.");
Console.WriteLine("2. Filtered File Listing.");
Console.WriteLine("3. FolderStatistics.");
Console.WriteLine("4. Quit.");
mainMenuChoice = int.Parse(Console.ReadLine());
if (mainMenuChoice == 1)
{
Option1();
}
if (mainMenuChoice == 2)
{
Option2();
}
if (mainMenuChoice == 3)
{
Option3();
}
if (mainMenuChoice == 4)
{
}
else
{
Console.WriteLine("you didnt enter a valid input! try again.");
}
}
答案 0 :(得分:5)
将读数从命令行更改为
if(Int32.TryParse(Console.ReadLine(), out mainMenuChoice))
{
if (mainMenuChoice == 1)
Option1();
else if (mainMenuChoice == 2)
Option2();
else if (mainMenuChoice == 3)
Option3();
else if (mainMenuChoice == 4)
Option4();
else
Console.WriteLine("you didnt enter a valid input! try again.");
}
else
{
Console.WriteLine("you didnt enter a valid input! try again.");
}
并在TryParse的else部分中为您的用户重复警告消息if。
当命令行中的字符无法转换为整数并分配给out参数mainMenuChoice
时,Int32.TryParse返回false。
答案 1 :(得分:4)
改为使用int.TryParse
:
if (!int.TryParse(Console.ReadLine(), out mainMenuChoice))
{
Console.WriteLine("That's not a number!");
}
...
但事实上,你实际上从未将输入用作一个数字,所以没有必要解析它。你可以把它留作一个字符串:
bool retry;
do
{
retry = false;
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Full File Listing.");
Console.WriteLine("2. Filtered File Listing.");
Console.WriteLine("3. FolderStatistics.");
Console.WriteLine("4. Quit.");
string mainMenuChoice = Console.ReadLine();
switch(mainMenuChoice)
{
case "1":
Option1();
break;
case "2":
Option2();
break;
case "3":
Option3();
break;
case "4":
break;
default:
Console.WriteLine("You didn't enter a valid input! Try again.");
retry = true;
break;
}
} while(retry);
此外,虽然这非常清晰且易于准备,但实际上 {/ 1}}变量并非如此。虽然它的工作方式不太明显(我可能会因此而避免使用它),但你可以像这样构建你的循环:
retry
答案 2 :(得分:0)
while(true)
{
int menuChoice;
string userInput = Console.Readline();
if(Int32.TryParse(userInput, out menuChoice))
{
if(menuChoice >= 1 && menuChoice <= 4)
RunCommand(menuChoice);
else
Console.WriteLine("Enter a number between 1-4");
}
else
Console.WriteLine("A number between 1-4 is required!");
}
答案 3 :(得分:0)
在Int上使用TryParse方法(详情here)。
例如:
int menuChoice;
if(!int.TryParse(Console.Readline(),out menuChoice){
Console.WriteLine("The menu choice you made was invalid.");
} else {
//do the rest of your code here
}