C#如何将数字输入限制为单个数字

时间:2015-07-10 01:28:34

标签: c# integer digit

抱歉,对于C#来说这可能很容易,我需要将这里的输入限制为一位数。

 int value, value1, value2, value3, value4;
 int resultFinal, resultFirst, resultSecond, resultThird = 0;

        Console.WriteLine("Enter five single digit numbers");

        value = Convert.ToInt16(Console.ReadLine());
        value1 = Convert.ToInt16(Console.ReadLine());            
        value2 = Convert.ToInt16(Console.ReadLine());
        value3 = Convert.ToInt16(Console.ReadLine());
        value4 = Convert.ToInt16(Console.ReadLine());


        resultFirst = value - value1;
        resultSecond = value2 - value3;      
        resultThird = resultFirst + resultSecond;
        resultFinal = resultThird + value4;
        Console.WriteLine("Answer: {0}", resultFinal);
        Console.WriteLine("Press any button to close");
        Console.ReadLine();

1 个答案:

答案 0 :(得分:1)

Console.WriteLine("Enter five single digit numbers");
List<int> list = new List<int>();
do
{
    var keyNumber = (int)Console.ReadKey(true).KeyChar;
    if (keyNumber >= 48 && keyNumber <= 57)
    {
        Console.WriteLine("Your input number is:" + (char)keyNumber);
        list.Add(keyNumber-48);
    }
    else
    {
        Console.WriteLine("Sorry, but please enter single digit numbers!");
    }
}
while (list.Count < 5);
var resultFirst = list[0] - list[1];
var resultSecond = list[2] - list[3];
var resultThird = resultFirst + resultSecond;
var resultFinal = resultThird + list[4];
Console.WriteLine("Answer: {0}", resultFinal);
Console.WriteLine("Press any button to close");
Console.ReadLine();

因为您只想让用户输入单个数字,我认为Console.ReadKey(true)更好