并非所有代码路径都返回一个值for循环

时间:2017-01-19 11:29:28

标签: c# for-loop methods return

此代码将比较存储在文本文件中的用户名密码。我认为这是因为for循环,它可能很简单,但我无法看到它。

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

2 个答案:

答案 0 :(得分:5)

如果users数组,则不会返回任何值。

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

可能,您必须在循环

下添加return 0;

作为进一步改进,您可以使用 Linq 重新编写方法(如果文件包含带有用户名的任何记录,则返回1 密码,否则为0

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

答案 1 :(得分:1)

你必须添加return 0;在循环之后,如果用户的大小为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;
    }