此代码将比较存储在文本文件中的用户名和密码。我认为这是因为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;
}
}
答案 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;
}