not all code paths return a value, for loop

时光毁灭记忆、已成空白 提交于 2021-02-17 03:22:35

问题


This code will compare usernames and passwords that are stored in a text file. I think it is because of the for loop, it is probably simple but I cant see it.

public int loginCheck()
{ 
    //-----------------------------------------------------------------
    string[] users = File.ReadLines("Username_Passwords").ToArray();
    //line of text file added to array 
    //-----------------------------------------------------------------

    for (int i = 0; i < users.Length; i++)
    {
        string[] usernameAndPassword = users[i].Split('_');
        //usernames and passwords separated by '_' in file, split into two strings

        if (_username == usernameAndPassword[0] && _password == usernameAndPassword[1])
        {
            return 1;
            //return 1, could have used bool
        }
        else
        {
            return 0;
        }
    }

回答1:


You don't return any value if users is an empty array.

string[] users = File.ReadLines("Username_Passwords").ToArray();

// if users is empty, users.Length == 0 and the loop isn't entered
for (int i = 0; i < users.Length; i++) 
{
   ...
}  

// no value is returned 

return 0; // <- suggested amendment

probably, you have to add return 0; below the loop

As the further improvement you can re-write the method using Linq (return 1 if file contains any record with required username and password, 0 otherwise):

public int loginCheck() {
  return File
    .ReadLines("Username_Passwords")
    .Select(line => line.Split('_'))
    .Any(items => items.Length >= 2 && 
                  items[0] == _username &&
                  items[1] == _password) 
   ? 1
   : 0;
}



回答2:


You have to add return 0; after your loop, no return block is reached if users is of size 0.

    public int loginCheck() {
        //-----------------------------------------------------------------
        string[] users = File.ReadLines("Username_Passwords").ToArray();
        //line of text file added to array 
        //-----------------------------------------------------------------
        for (int i = 0; i < users.Length; i++) {
            string[] usernameAndPassword = users[i].Split('_');
            //usernames and passwords separated by '_' in file, split into two strings

            if (_username == usernameAndPassword[0] && _password == usernameAndPassword[1]) {
                return 1;
                //return 1, could have used bool
            }
        }
        return 0;
    }


来源:https://stackoverflow.com/questions/41740695/not-all-code-paths-return-a-value-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!