gpt4 book ai didi

c# - 没有匹配项时如何跳出无限循环?

转载 作者:行者123 更新时间:2023-11-30 14:50:51 24 4
gpt4 key购买 nike

所以我正在尝试测试我的验证,当用户输入错误的 5 位数字时,它将显示错误并返回到原始表单。但是,我的代码使代码进入无限循环,因此我无法在我的表单上做任何其他事情,因为循环永远不会结束。

public bool findCustomer(string accountNumber)
{
string record = Global.currentFile.getNextRecord(); //gets first record
bool okay = Global.customer.matchCustomer(accountNumber, record); //checks if it matches
while (!okay == true) //if it does not match, get next record and check again until it reaches end of file
{
record = Global.currentFile.getNextRecord();
okay = Global.customer.matchCustomer(accountNumber, record);
}

return okay;
}//end method

这是另一个类的获取记录方法

public string getNextRecord()
{
string nextRecord = String.Empty;

while ((nextRecord = reader.ReadLine()) != null)
{
return nextRecord;
}

return nextRecord;
}// end getNextRecord

这是文本文件

 12345 * Shrek * 1209 * 100000 * 50000
12077 * Sammy Wheeler * 1207 * 5000 * 0
99999 * The Big Grump * 1298 * 1500000 * 1500000
13579 * Brooks Robinson * 5555 * 225000 * 225000
24680 * Johnny Unitas * 1919 * 60000 * 34000
68420 * Y. A. Tittle * 1414 * 42000 * 12000
23456 * Hilary Clinton * 2222 * 65000 * 123456
23232 * Julianne Baird * 1234 * 145000 * 12321

最佳答案

您应该处理 getNextRecord() 返回 null 或空字符串的情况

while (!okay)                                                       
{
record = Global.currentFile.getNextRecord();
if (string.IsNullOrWhiteSpace(record)
break;
okay = Global.customer.matchCustomer(accountNumber, record);
}

请注意,如果文件的数据中间包含一个空字符串,那么这将失败,并且该空行之后的行将被转义。

为什么要检查 nullstring.Empty?因为如果读取器到达文件末尾,则 nextRecord 为空。

关于c# - 没有匹配项时如何跳出无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com