初级开发人员,1到9个问题控制台命令

时间:2018-09-22 21:49:22

标签: c# console-application

最近,我开始学习编程,主要是从理论开始,然后才着手使用计算机,问题是,我需要通过视觉工作室的控制台来构建程序,问题是:需要选择一个1到9之间的数字,在他选择了该数字之后,您必须使程序显示为“您选择的数字为” X“”

我确实是一个初学者,我不知道如何仅验证数字1到9。

1 个答案:

答案 0 :(得分:1)

Here is an example that uses int.TryParse to check if the input you gave is really a number (integer). The while loop iterates until the input you gave meets your criteria.

Console.WriteLine("Pick a number from 1 to 9");
int num;
while(!int.TryParse(Console.ReadLine(), out num) || num < 1 || num > 9)
{
     Console.WriteLine("Your entry was wrong!");
     Console.WriteLine("Pick a number from 1 to 9");
}
Console.WriteLine($"The number you picked is {num}");
Console.ReadKey();