问题
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