c# - 并非所有代码路径都应在需要时返回值

标签 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;
            }
        }
    }
}

我通过另一行在本地作用域中定义的过程从此行传入我的值。
stockID = checkIDNumber(stockID);

这是完整的代码:
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.....

        }

    }
}

}

最佳答案

问题是您只从else块内部返回一个值。

无论程序通过代码采用哪种路径,方法都需要返回一个值。您可以根据需要以多种方式解决此问题。例如,您可以在方法的底部有一个“包罗万象”的返回值,以便如果它通过所有测试(即if块)并到达底部,只要这是有意义的结果,它将返回全面的值(value)。

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

同样,这完全取决于您的需求。

关于c# - 并非所有代码路径都应在需要时返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983340/

相关文章:

c# - 在 ListView 中过滤数据 [mvvm]

c# - VS2010 不会在 64 位版本的 Windows 上的 WinForms 应用程序中显示未处理的异常消息

c# - 在 UITableView 的编辑模式下允许多重选择

c# - 在 Projection.Conditionals 中添加多个条件以进行查询

error-handling - 用于获取工作日志的 JIRA REST API - "You do not have the permission to see the specified issue"

linux - Linux中可用于删除文件的系统调用

php - PHP Whoops错误处理程序电子邮件

R 插入符包错误 - 至少一个类级别不是有效的 R 变量名称

c++ - 显示垃圾值的二进制文件处理程序 (Turbo C++)

Python - 如何一次读取文件一个字符?