[英]c# empty string[] error
有人請幫我處理這段代碼,它顯示array outofbond exception
。
文件new_hosts.txt中的數據類似於:
test test 28/6/2015 09:45 PM
test fafagf 30/6/2015 01:00 PM
test sfaasfag 28/6/2015 10:05 PM
碼:
public void notification()
{
string regvalue;
int ctr = 0;
bool isNotificationExits=false;
string[] meetingdata=new string[]{};
string[] notificationsdata = new string[]{};
try
{
//ctr = File.ReadAllLines("new_hosts.txt").Length;
meetingdata = File.ReadAllLines("new_hosts.txt");
}
catch (FileNotFoundException)
{
//showmainmenu();
}
List<String> notificationsdata = new List<String>();
foreach(string data in meetingdata)
{
string trimed = data;
//Console.WriteLine(data);
Regex d = new Regex(@"(\d+[\/]\d+[\/]\d+)");
Regex t = new Regex(@"(\d+)([\:])(\d+)\s(PM|AM)");
Match mt =t.Match(trimed);
Match md = d.Match(trimed);
regvalue = md.Value +" " +mt.Value;
DateTime datetime = new DateTime();
if (md.Success && mt.Success)
{
datetime = DateTime.ParseExact(regvalue, "d/M/yyyy hh:mm tt", new CultureInfo("en-US"), DateTimeStyles.None);
//Console.Write(datetime);
}
else { Console.WriteLine("Opps someting Went Wrong Please Contact Developer...!!!"); }//this is not going to happend ever
if (!(datetime < DateTime.Now))
{
if (datetime <= DateTime.Now.AddDays(5))
{
//Console.WriteLine(ctr + " you here");
isNotificationExits = true;
notificationsdata[ctr]=data; <<-----Array Out Of bond Exception here
ctr++;
}
}
}
if(isNotificationExits==true)
{
Console.WriteLine("\n\t\tHey..! You have Some Reminders here\n ");
Console.Write("Sr.no |");
Console.Write(" Subject |");
Console.Write(" Place |");
Console.Write(" Date |");
Console.WriteLine(" Time");
for(int j=0; j <= notificationsdata.Length ; j++)
{
Console.WriteLine(j + 1);
Console.WriteLine(notificationsdata[j]);
}
Console.WriteLine();
}
}
除了Nikola之外,您還需要解決的問題是您尚未設置數組的大小
string[] notificationsdata = new string[]{};
如果您不知道提前的大小,則可以使用其他數據結構,例如List<string>
。 我看到您創建了一個List<string>
對象,但是您將其命名為與數組相同的名稱。 這很令人困惑,因此您應該重命名其中之一或刪除其中之一。
要使用列表,請替換
notificationsdata[ctr]=data;
同
notificationsdata.Add(data);
您沒有指定要在何處確切地獲得異常,但是我會(不是這樣)大膽猜測,並告訴您這段代碼是您遇到的錯誤:
for(int j=0; j <= notificationsdata.Length ; j++)
{
Console.WriteLine(j + 1);
Console.WriteLine(notificationsdata[j]);
}
問題是,您要從索引0開始遍歷數組,直到索引notificationsdata.Length
為止。 但是, Length
方法返回數組中的項數,因此不存在帶有數組長度的索引。
您可以采取的措施只是將小於或等於符號更改為小於:
for(int j=0; j < notificationsdata.Length; j++)
或從循環最大值中減去一個:
for(int j=0; j <= notificationsdata.Length - 1; j++)
如果使用列表,則必須使用notificationsdata.Add(data)
將項目添加到列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.