并非所有代码路径都应该返回值

Rob*_*old 0 c# error-handling file-handling

试图在控制台应用程序中完成一个库存系统,因此我被困在这一部分,以确保用户不能有一个重复的8位长的ID号,我的问题如下.

基本上我不确定为什么这个代码不起作用,我可能在这里错过了一段非常明显的代码,帮助将被赞赏,已经尝试改变已经存在的值,所以有可能忽略了一个值.

static int checkIDNumber(int ID)
{
    // Check the number passed in & then loop through all the lines...
    // If number is taken then output error, because id exists already
    // Else allow the value to be used in the stock system.

    int IDNumber = ID;
    using (StreamReader sr = new StreamReader("Stockfile.txt"))
    {
        string lineValues;

        while (sr.EndOfStream == false)
        {
            lineValues = sr.ReadLine();

            if (lineValues.Contains(IDNumber.ToString()))
            {
                Console.WriteLine("Id number is currently already taken.");
            }
            else
            {
                return IDNumber;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在另一个过程中从这一行传入我的值,它在本地范围内定义.

stockID = checkIDNumber(stockID);
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

class Program
{
    static void Main(string[] args)
    {
        char menuOption = '0';

        while (menuOption != '3')
        {
            DisplayMenuOption();
            menuOption = GetMenuOption();

            switch (menuOption)
            {
                case '1':
                    AddStock();
                    break;

                case '2':
                    CheckStock();
                    break;

                case '3':
                    Console.WriteLine("Goodbye");
                    break;

                default:
                    Console.WriteLine("That is not a valid option");
                    break;

            }
        }


            // Keep it all happy for a screenshot ;)
            Console.ReadLine();

    }

    static void DisplayMenuOption()
    {
        Console.WriteLine("Do you wish to Add Stock(1) or Check Stock(2) or Exit(3)?");
    }

    static void DisplayStockOption()
    {
        Console.WriteLine("Do you want to search by ID(1) or by Name(2), Delete current stock(3) or Exit(4)?");
    }

    static char GetMenuOption()
    {

        char userChoice = '0';

        userChoice = Convert.ToChar(Console.ReadLine());
        return userChoice;
    }

    static void CheckStock()
    {
        char menuOption = 'a';
        while (menuOption != '4')
        {
            DisplayStockOption();
            menuOption = GetMenuOption();

            switch (menuOption)
            {
                case '1':
                    SearchID();
                    break;

                case '2':
                    SearchName();
                    break;

                case '3':
                    RemoveStock();
                    break;

                case '4':
                    Console.WriteLine("Goodbye");
                    break;

                default:
                    Console.WriteLine("That is not a valid option");
                    break;

            }
        }
    }

    static void RemoveStock()
    {
        List<string> tempList = new List<string>();
        string lineValues = "";
        bool found = false;
        int ID = 0;

        using (StreamReader sr = new StreamReader("Stockfile.txt"))
        {

            Console.Write("Please enter the ID number to delete: ");
            ID = Convert.ToInt32(Console.ReadLine());

            while (sr.EndOfStream == false)
            {
                lineValues = sr.ReadLine();

                if (lineValues.Contains(ID.ToString()) == false)
                {
                    tempList.Add(lineValues);
                }
                else
                {
                    found = true;
                }
            }
        }

        if (found == true)
        {
            using (StreamWriter sw = new StreamWriter("Stockfile.txt", false))
            {
                for (int i=0; i < tempList.Count; i++)
                {
                    sw.Write(tempList[i]);
                    sw.WriteLine();
                }
            }
        }
    }

    static void SearchName()
    {
        using (StreamReader sr = new StreamReader("Stockfile.txt"))
        {
            string name;

            Console.Write("Please enter the name: ");
            name = Console.ReadLine();


            while (sr.EndOfStream == false)
            {

                string lineValues = sr.ReadLine();

                if (lineValues.Contains(name))
                {
                    Console.WriteLine("{0}", lineValues);
                }
                else
                {
                    Console.WriteLine("{0} does not exist in this stock system!",name); // Could try to match a similar string incase of spelling errors here, although after looking at it it may be a bit far for what is being required now, but in the real world application this would be a must else people would mistype words thus not having an exact match.
                }
            }
        }
   }



        static void SearchID()
    {

        using (StreamReader sr = new StreamReader("Stockfile.txt"))
        {
            int IDNumber;
            string lineValues;

            Console.Write("Please enter the ID number: ");
            IDNumber = Convert.ToInt32(Console.ReadLine());


            while (sr.EndOfStream == false)
            {

                lineValues = sr.ReadLine();

                if (lineValues.Contains(IDNumber.ToString()))
                {
                    Console.WriteLine("{0}", lineValues);
                }
                else
                {
                    Console.WriteLine("{0} does not exist in this stock system!", IDNumber); // Could try to match a similar string incase of spelling errors here, although after looking at it it may be a bit far for what is being required now, but in the real world application this would be a must else people would mistype words thus not having an exact match.
                }
            }
        }
    }

    static int checkIDNumber(int ID)
    {
        // Check the number passed in & then loop through all the lines...
        // If number is taken then output error, becuase id exists already
        // Else allow the value to be used in the stock system.


        using (StreamReader sr = new StreamReader("Stockfile.txt"))
        {
            int IDNumber;
            string lineValues;

            Console.Write("Please enter the ID number: ");
            IDNumber = Convert.ToInt32(Console.ReadLine());


            while (sr.EndOfStream == false)
            {

                lineValues = sr.ReadLine();

                if (lineValues.Contains(IDNumber.ToString()))
                {
                    Console.WriteLine("Id number is currently already taken.");
                }
                else
                {
                    ID = IDNumber;
                    return ID;
                }
            }
        }


    }

    static void AddStock(int IDNumber)
    {

        using (StreamWriter sw = new StreamWriter("Stockfile.txt", true))
        {
            int stockID = 0;
            int stockQuantity = 0;
            double stockPrice = 0.00;
            string stockName = "";
            string s = ""; // Being Lazy here, to convert to when needed.

            while (stockID.ToString().Length != 8)
            {
                Console.Write("Please enter the stock ID number: ");
                stockID = Convert.ToInt32(Console.ReadLine());

            }

            s = stockID.ToString();
            sw.Write(s + "\t"); // Will only accept an 8 figure digit so is safe to have a single value here.

            while (stockName.Length <= 2) // No fancy brands here......
            {
                Console.Write("Please enter the name of the stock: ");
                stockName = Console.ReadLine();
            }

            s = stockName;
            sw.Write(s + "\t");

            while (stockQuantity < 1) // Running a small shop here...
            {
                Console.Write("Please enter the quanity of stock: ");
                stockQuantity = Convert.ToInt32(Console.ReadLine());
            }

            s = stockQuantity.ToString();
            sw.Write(s + "\t");

            while (stockPrice < 0.01) // Running a very small shop....
            {
                Console.Write("Please enter the price of the stock: ");
                stockPrice = Convert.ToDouble(Console.ReadLine());
            }

            s = stockPrice.ToString();
            sw.Write(s + "\t");

            sw.WriteLine(); // TO create the new line.....

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

}

ror*_*.ap 7

问题是你只是从else块内部返回一个值.

无论程序通过代码执行哪条路径,您的方法都需要返回一个值.您可以通过多种方式解决此问题,具体取决于您的要求.例如,你可以在方法的底部有一个"catch-all"返回值,这样如果它通过你所有的测试(即if块)并到达底部,只要这是一个有意义的结果,它将返回全能价值.

或者,您可以确保return在每个代码路径中放置一个语句.为此,你需要return在块的if一部分中添加一个if,但是你可能还需要在while循环之外返回,因为它可能永远不会执行.

同样,这一切都取决于您的需求.

  • 你可以用一个return语句来完成它.你这样做的方法是在方法的顶部创建一个变量,只需在需要设置它的地方设置它,然后在方法的末尾返回该变量.根据我的经验,如果它使您的代码更简洁和可读,并且更重要的是,不那么脆弱或容易出错,那么获得多个返回并不是一个坏习惯. (6认同)