not all code paths return a value, for loop(并非所有代码路径都返回值,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;
}
}
推荐答案
如果 users
是 empty 数组,则不会返回任何值.
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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:并非所有代码路径都返回值,for循环
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01