如何使用C#中的方法存储变量?

Roz*_*Roz -1 c# methods boolean try-catch do-while

我在下面的代码中遇到了一些问题.我还在学习,我不知道如何修复它.

1.我想要做的是创建一个方法(GetInt)来存储变量,就像我想要在第二个方法(GetTrack)中那样进入我的main方法.

2.-当无效输入时我无法获取GetInt方法循环,​​我猜测try/catch和boolean thingy有问题

谢谢

//Get int Method
static public void GetInt(string sPrompt, int iMin, int iMax)
{
    int iNum;
    bool bError = false;

    do
    {
        bError = true;
        try
        {
            Console.Write(sPrompt);
            iNum = int.Parse(Console.ReadLine());
            if ((iNum < iMin) || (iNum > iMax))
            {
                Console.WriteLine("The value is out of range.");
                bError = true;
            }
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An invalid number was entered, please try again.");
            bError = true;
        }
    }
    while (bError == false);
}

//Get Track Method
static public void GetTrack()
{
    int iMin;
    int iSec;

    iMin = GetInt("Enter the minutes: ", 0, 10);
    iSec = GetInt("Enter the seconds: ", 0, 59);
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*nen 6

GetInt您开始时立即设置bError为true.这很可能应该是假的,所以你实际上会循环,因为你没有将它设置为false.

此外,您不会从方法中返回任何内容,因此您无法获得任何回报.您必须更改返回的方法,int并在获得该值时实际返回该值.