并非所有代码路径都返回一个值,用于循环 [英] not all code paths return a value, for loop
本文介绍了并非所有代码路径都返回一个值,用于循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码将比较存储在文本文件中的用户名和密码.我认为这是因为for循环,它可能很简单,但我看不到它.
public int loginCheck(){//-----------------------------------------------------------------string [] users = File.ReadLines("Username_Passwords").ToArray();//将一行文本文件添加到数组//-----------------------------------------------------------------为(int i = 0; i< users.Length; i ++){string [] usernameAndPassword = users [i] .Split('_');//在文件中用"_"分隔的用户名和密码,分为两个字符串如果(_username == usernameAndPassword [0]&&__ password == usernameAndPassword [1]){返回1;//返回1,本来可以使用bool}别的{返回0;}}
解决方案
如果 users
是 empty 数组,则不返回任何值.
string [] users = File.ReadLines("Username_Passwords").ToArray();//如果用户为空,则users.Length == 0并且不进入循环为(int i = 0; i< users.Length; i ++){...}//没有返回值返回0;//<-建议的修正
可能您必须在循环下方添加 return 0;
作为进一步的改进,您可以使用 Linq 重新编写该方法(如果文件包含带有所需的 any 记录,则返回 1
用户名和密码,否则为 0
):
public int loginCheck(){返回文件.ReadLines("Username_Passwords")选择(线=> line.Split('_')).Any(items => items.Length> = 2&&items [0] == _username&&items [1] == _密码)?1个:0;}
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;
}
}
解决方案
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;
}
这篇关于并非所有代码路径都返回一个值,用于循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文