We are trying to load data into an array using code given to us by the teacher. The code is given to us because we have not and will not learn any of it, but there seems to be a problem with it. Public void LoadData() is the method he gave to us. We were to add code to store it into our array.
What I have added is the two lines of code that are denoted with ** on either side. This was what the tutor instructed us to do, but they are also stumped with the problem we have. We keep getting the NullReferenceException was unhandled, object reference is not to an instance object error.
The tutors can’t seem to figure it out, and we searched the internet and worked for hours trying to find a solution. I’ll also add that when tinkering with possible solutions, the error would sometimes point to a different location. The solutions I have read don’t seem to be working. Some say it’s the way I may be declaring my array, and some say add something like if (r!=null) as a null check (which we have never learned anything about) I tried adjusting to their advice and either it didn’t work, or I’m just putting it in the wrong place.
Please take a look at the code and see what is missing. Please understand, we are in a fundamentals class. We don’t know what null checks are, what stack traces are, or anything advanced. I’ve excluded some methods that I know to be correct and would just clutter everything. You will see where I’ve created the array called scores, and the public void data that was copy and pasted.
It seems to be something wrong with the s and r variables that are in included in the LoadData() code, or the way I declared the scores array. Maybe it's something else.
using System; using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace DataAnalysis
{
class TestScores
{
int[] scores;
private double[] counter;
private int count;
public TestScores()
{
count = 0;
scores = new int[100];
LoadData();
for (int i = 0; i < scores.Length; i++)
{
count++;
}
}
public void LoadData()
{
int i = 0;
StreamReader r = null;
string path = "C:\\IST600Work\\testscore.txt";
String s;
try
{
r = new StreamReader(path);
while (!r.EndOfStream)
{
s = r.ReadLine(); // Reads one testscore data, as a string
**scores[i] = int.Parse(s);
**
**i++;
**
// Add code here to store it to your array
}
}
catch (FileNotFoundException n)
{
Console.WriteLine("File to read not found");
}
catch (IOException o)
{
Console.WriteLine(o.Message);
}
finally
{
r.Close();
r.Dispose();
}
}
}
}