并非所有代码路径都返回值,for循环

编程入门 行业动态 更新时间:2024-10-26 20:31:05
本文介绍了并非所有代码路径都返回值,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循环

本文发布于:2023-11-10 01:18:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573965.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   返回值   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!