我找不到关于如何将用户输入分配为可在其他地方作为整数使用的明确答案,而不会使程序因无效的键输入而崩溃。我也不确定将输入设置为整数是否是个好主意,因为这是我知道的唯一方法。这是代码:
int atkchoice = Convert.ToInt32 (Console.ReadLine());
这是我想将输入用作整数的方式:
if (atkchoice == 1)
{
我找不到关于如何将用户输入分配为可在其他地方作为整数使用的明确答案,而不会使程序因无效的键输入而崩溃。我也不确定将输入设置为整数是否是个好主意,因为这是我知道的唯一方法。这是代码:
int atkchoice = Convert.ToInt32 (Console.ReadLine());
这是我想将输入用作整数的方式:
if (atkchoice == 1)
{
如果您使用 Convert.ToInt32(),如果输入不是数字,您可能会遇到异常。使用 TryParse() 方法更安全。
int atkchoice;
do
{
// repeat until input is a number
Console.WriteLine("Please input a number! ");
} while (!int.TryParse(Console.ReadLine(), out atkchoice));
Console.WriteLine("You entered {0}", atkchoice);
如果要验证输入是否在一组数字中,可以创建用户选择的枚举,然后检查输入是否正确。使用 Enum.IsDefined 验证值是否在枚举中。
enum UserChoiceEnum
{
Choice1 = 1,
Choice2,
Choice3
}
void Main()
{
int atkchoice;
do
{
do
{
// repeat until input is a number
Console.WriteLine("Please input a number! ");
} while (!int.TryParse(Console.ReadLine(), out atkchoice));
} while (!Enum.IsDefined(typeof(UserChoiceEnum), atkchoice));
Console.WriteLine("You entered {0}", atkchoice);
}
请参考this(链接到stackoverflow中的另一个类似问题)C# char to int。我想它会回答你的大部分问题..(对于你上面的评论 - “谢谢你这很好,但现在我很好奇我是否可以将它设置为以相同的方式响应其他数字的字符输入,允许用户只使用 1 2 和 3。什么方法最好?")
如果您有多个值要检查,您可以将它们添加到 aList
并检查此列表是否包含您的值(使用方法Contains
)。您可以循环使用,while
直到输入有效。
之后,由于您的期望值都是数字,因此您可以安全地将输入转换为int
with Convert.ToInt32
。
public static void Main(string[] args)
{
IEnumerable<string> allowedInputs = new[] {"1", "2", "3"};
string userInput = "";
while (!allowedInputs.Contains(userInput))
{
Console.WriteLine("Enter 1, 2 or 3");
userInput = Console.ReadLine();
}
int atkChoice = Convert.ToInt32(userInput);
//Do your if conditions
}