本文介绍了并非所有代码路径都返回值,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循环
发布评论