从数组中删除数据时遇到问题
Posted
技术标签:
【中文标题】从数组中删除数据时遇到问题【英文标题】:having trouble removing data from arrays 【发布时间】:2019-08-16 07:58:44 【问题描述】:我在搜索“销售代表姓名”的数组然后删除姓名、销售和佣金时遇到问题。
static void RemoveSale(string[] sellerNames, double[] sellerSales, double[] sellerCommision, ref int sellerCount)
int index;
string salesRep;
try
if (sellerCount > 0)
salesRep = GetValidName("Enter the sales rep to delete");
index = SearchSeller(sellerNames, sellerCount);
if (index == -1)
Console.WriteLine("that sales rep is not on the team");
else
sellerSales[index] = sellerSales[sellerCount - 1];
sellerNames[index] = sellerNames[sellerCount - 1];
sellerCommision[index] = sellerCommision[sellerCount - 1];
Console.WriteLine("Sales rep 0 has been deleted.", sellerNames);
sellerCount--;
else
Console.WriteLine("there are no sales reps to delete");
catch (Exception ex)
Console.WriteLine(ex.Message);
Console.ReadLine();
static int SearchSeller(string[] sellerNames, int sellerCount)
try
int index = 0;
bool found = false;
while (!found && index < sellerCount)
if (sellerNames[sellerCount] == sellerNames[index])
found = true;
else
index++;
if (!found)
index = -1;
return index;
catch (Exception ex)
Console.WriteLine(ex.Message);
Console.ReadLine();
return 0;
预期结果是删除名称、数据,并确认 SellerName0 已被删除。
实际结果是什么都没有被移除,并且没有确认被移除的卖家
【问题讨论】:
【参考方案1】:您没有将salesRep
对象传递给搜索功能。假设您可以更改搜索功能的签名,请尝试以下操作:
// Pass the name of the sales rep
static int SearchSeller(string[] sellerNames, int sellerCount, string salesRep)
try
int index = 0;
bool found = false;
while (!found && index < sellerCount)
// compare the current name in array with the passed name
if (salesRep == sellerNames[index])
found = true;
else
index++;
if (!found)
index = -1;
return index;
catch (Exception ex)
Console.WriteLine(ex.Message);
Console.ReadLine();
return 0;
调试通常应该是检查容易出错的第一步。
更好的搜索选择是使用 c# 函数Find
Array.Find(sellerNames, salesRep);
【讨论】:
就是这样!谢谢。在作业到期之前,我已经完成了最后几次错误检查。你的救命恩人!!不幸的是,老师不允许我们使用查找、排序或列表以上是关于从数组中删除数据时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章