重试直到用户输入正确

Ian*_*ter 2 c#

我正在通过Rob Miles黄皮书学习C#并且遇到了理解变量范围的问题.

我开发的课程(在底部)要求输入一个数字,然后将其显示给用户.我想增强它,以便如果用户输入10而不是10,它输出一条消息,并且用户有另一次尝试.

这是迄今为止在改变中的几次尝试之一......

...

    static int readInt(string prompt, int low, int high)
    {
        int result;

        do
        {
            try
            {
                string intString = readString(prompt);
                result = int.Parse(intString);
                Console.WriteLine("Thank you");
            }
            catch
            {
                Console.WriteLine("Invalid age value");
            }

        } while ((result < low) || (result > high));

        return result;
    }
...
Run Code Online (Sandbox Code Playgroud)

不幸的是,这有效(我认为)推出result范围,因为有了这个改变,我看到以下补充错误:

CS0165使用未分配的局部变量'result'

实现这一目标的C#方式是什么?

完整的课程:

using System;

class Exception1
{
    static string readString(string prompt)
    {
        string result;

        do
        {
            Console.Write(prompt);
            result = Console.ReadLine();
        } while (result == "");

        return result;
    }

    static int readInt(string prompt, int low, int high)
    {
        int result;

        do
        {            
            string intString = readString(prompt);
            result = int.Parse(intString);            
        } while ((result < low) || (result > high));

        return result;
    }


    public static void Main()
    {
        const int SCORE_SIZE = 1;

        int[] scores = new int[SCORE_SIZE];

        for (int i = 0; i < SCORE_SIZE; i++)
        {
            scores[i] = readInt("Score : ", 0, 1000);

        }

        for (int i = 0; i < SCORE_SIZE; i++)
        {
            Console.WriteLine("Score " + i + " is " + scores[i]);
        }

        Console.Read();
    }
}    
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 6

编译器不知道while循环实际运行(它可以在分配之前抛出和异常result)并设置一个值result.因此它抱怨这一点.

您可以通过为以下内容分配默认值来避免这种情况result:

int result = -1;
Run Code Online (Sandbox Code Playgroud)

或者通过在catch块中设置值:

catch
{
    result = -1;
    Console.WriteLine("Invalid age value");
}
Run Code Online (Sandbox Code Playgroud)

我总是-1在这些情况下用作"这个值有问题"的指标.