如何强制控制台只接受一定范围内的数字?

时间:2017-10-11 03:06:27

标签: c# console-application

我有这个代码,我输入一个名字,然后是一个整数。然后,应用程序将根据指定的整数重复输入的名称。我遇到的问题是,我只希望用户能够重复名称最多10次,最小值为1.这是我到目前为止所拥有的。

Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();

Console.Write("Enter the number of times you wish for me to repeat your name, " + Name );
int number = Int32.Parse(Console.ReadLine());

for (int i = 0; i < number; i++)        
    Console.WriteLine(""+ Name);
Console.ReadKey();

编辑:如果有人看到了一种更简单的方式来做我所拥有的,我会很乐意提出建议!

3 个答案:

答案 0 :(得分:1)

body{
    margin: 0px;
    font-family: sans-serif;
    font-size: 2em;
}

.flex-container{
    /* flexbox properties*/
    display: -webkit-flex;
    -webkit-flex-direction: row;
}

.flex-container-column{
    display: -webkit-flex;
    -webkit-flex-direction: column;
}

.flex-item{
    /*flexbox properties*/
    display: -webkit-flex;
    align-items: center;
    justify-content: center;
}

.header{
    height: 50px;
    background-color: tomato;
    margin: 0;
    border-bottom: 3px solid rgba(0,0,0,0.3);
}

ul{
    justify-content: flex-end;
}

.nav{
    flex-direction: row;
    margin: 2px;
    padding: 0 10px 0 10px;
    background-color: rgba(0,0,0,0.2);
    color: white;
}

.content{
    height: auto;
    margin: 0px;
}

.sidebar{
    background-color: grey;
    flex: 1;
}

.main{
    background-color: lightgrey;
    flex: 2;
    min-height: 1000px;
}

footer{
    height: 50px;
    border-top: 3px solid rgba(0,0,0,0.3);
    background-color: tomato;
}

答案 1 :(得分:1)

在打印名称之前,您需要过滤并验证输入数字是否最小为1,最大值为10。你可以这样做:

 Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
        string Name = Console.ReadLine();

        Console.Write("Enter the number of times you wish for me to repeat your name, " + Name);

        int number = 0;

        do
        {
            Int32.TryParse(Console.ReadLine(), out number);
            if (number > 10 || number < 1)
                Console.WriteLine("Please input numbers between 1 to 10");

        } while (number > 10 || number < 1);

            for (int i = 0; i < number; i++)
                Console.WriteLine("" + Name);
        Console.ReadKey();

我在这里做do-while循环。除非满足while循环,否则它将持续验证该数字是否在指定范围内,否则它将退出并将打印名称。

答案 2 :(得分:0)

您可以将ReadLine()包装在while语句中

示例是

int number = -1;
while(number < 1 || number > 10)
{
        //Input code
}
//for loop goes under here