배열의 각 요소의 출현을 계산하고 있지만 "값은 null이 될 수 없습니다"오류가 발생합니다. arr1이 마지막 5 개를 제외한 모든 null 값으로 채워지기 때문에 이것은 나에게 의미가 없습니다. null 인 요소배열의 카운팅 발생
여기 내 코드입니다. 나는 어딘가에 약간의 논리 오류가있을 수 있으므로 처음으로 사전을 사용하고 있습니다. 나는 텍스트 파일을 읽고있다.
string[] arr1 = new string[200];
StreamReader sr = new StreamReader("newWorkSheet.txt");
string Templine1 = "";
int counter = 0;
while (Templine1 != null)
{
Templine1 = sr.ReadLine();
arr1[counter] = Templine1;
counter += 1;
}
sr.Close();
// Dictionary, key is number from the list and the associated value is the number of times the key is found
Dictionary<string, int> occurrences = new Dictionary<string, int>();
// Loop test data
foreach (string value in arr1)
{
if (occurrences.ContainsKey(value)) // Check if we have found this key before
{
// Key exists. Add number of occurrences for this key by one
occurrences[value]++;
}
else
{
// This is a new key so add it. Number 1 indicates that this key has been found one time
occurrences.Add(value, 1);
}
}
// Dump result
System.IO.StreamWriter sr2 = new System.IO.StreamWriter("OrganizedVersion.txt");
foreach (string key in occurrences.Keys)
{
sr2.WriteLine("Integer " + key.ToString() + " was found " + occurrences[key].ToString() + " times");
}
sr2.Close();
Console.ReadLine();
편집 : 나는 여기에 선언문을 포함하여 모든 코드를 넣었습니다.
'arr1'과'counter'의 선언과 초기화를 보여줍니다. –