[英]not all code paths return a value, for loop
此代码将比较存储在文本文件中的用户名和密码 。 我认为这是因为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;
}
}
如果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;
}
您必须添加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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.