并非所有代码路径都返回值,for循环 [英] not all code paths return a value, for loop

查看:24
本文介绍了并非所有代码路径都返回值,for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

如果 usersempty 数组,则不会返回任何值.

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

可能,你必须在循环下面添加 return 0;

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

作为进一步的改进,您可以使用 Linq 重写方法(如果文件包含 any 记录和所需的,则返回 1用户名密码,否则为0):

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

这篇关于并非所有代码路径都返回值,for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆