0

I am trying to make a trivia game in c# using a console application. And I am having troubles getting the console to read the file. Currently what its doing is saying that the file could not be read and the the index was outside the bounds of the array. But then everything that is in the text file gets displayed. I am unsure on what I get the file could not be read but then the file gets displayed.

The file is a .txt file and here is what is looks like

What is another name for SuperMan?,the man of steel
What is Superman's only weakness?,kryptonite
What is the name of Batman's secret identity?,bruce wayne
Batman protects what city?,gotham city
How did Spiderman get his superpowers?,bitten by a radioactive sipder
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?,wonder woman
Which superhero has an indestructible sheild?,captain america
Which superhero cannot transformback into human form?,the thing
What villan got his distinctive appearance form toxic chemicals?,joker
What is the name of the archnemesis of the Fantastic Four?, dr doom

Here is the code that I have for reading and displaying the file.

static void Main(string[] args)
    {
        string filename = @"C:\Trivia\questions.txt";
        List<string> questions = new List<string>();
        List<string> answers = new List<string>();

        LoadData(filename, questions, answers);

        Console.WriteLine();
        questions.ForEach(Console.WriteLine);
        Console.WriteLine();
        answers.ForEach(Console.WriteLine);
    }

    static void LoadData(string filename, List<string> questions, List<string> answers)
    {
        try
        {
            using(StreamReader reader = new StreamReader(filename))
            {
                string line;

                while((line = reader.ReadLine()) != null)
                {
                    string[] lineArray = line.Split(',');
                    string annswer = lineArray[1];
                    string question = lineArray[0];
                    questions.Add(question);
                    answers.Add(annswer);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("File could not be read");
            Console.WriteLine(e.Message);
        }
    }

Here is the output on the console.

File could not be read
Index was outside the bounds of the array.

What is another name for SuperMan?
What is Superman's only weakness?
What is the name of Batman's secret identity?
Batman protects what city?
How did Spiderman get his superpowers?
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?
Which superhero has an indestructible sheild?
Which superhero cannot transformback into human form?
What villan got his distinctive appearance form toxic chemicals?
What is the name of the archnemesis of the Fantastic Four?

the man of steel
kryptonite
bruce wayne
gotham city
bitten by a radioactive sipder
wonder woman
captain america
the thing
joker
dr doom

Thanks for the suggestions.

5
  • 1
    You might want to check the the length of the array is 2 as expected. If you have a trailing newline in your file it will break for example.
    – Stuart
    Dec 4, 2019 at 23:22
  • 1
    Learning how to use the debugger will help you in resolving this and many other problems in your code. Dec 4, 2019 at 23:30
  • 1
    I don't believe the code you've shown can produce that output. Most likely the issue is that there's a blank line at the beginning of the file, and your code is failing on this line: string annswer = lineArray[1]; (you have hard-coded index 1 without first checking the size of the lineArray). However, in that case no other output would be shown than the error message. When I copy/paste your code and sample file contents, it works correctly, so something is different on your machine - either the code, the file contents, or both.
    – Rufus L
    Dec 4, 2019 at 23:31
  • @RufusL An extra line break at the end will produce that output.
    – LarsTech
    Dec 4, 2019 at 23:43
  • @LarsTech Ah, of course! I missed that the answers and questions were output separately, and was thinking that the error would be at the end of the output instead of the beginning in that case. Good catch.
    – Rufus L
    Dec 4, 2019 at 23:44

3 Answers 3

1

From playing around with your code, it looks like you might have some newlines at the end of your questions.txt file. Getting rid of those would fix your initial problem, but the real issue is that you're not checking each line to see if it contains a comma, nor are you discarding empty rows of data. Here's an approach that does both:

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    try
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            string[] lines= 
                reader.ReadToEnd() //Read the whole file
                .Trim() //Get rid of whitespace at the beginning and end of the file, no more random newlines at the end.
                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) //Separate each line AND remove any empty lines.
            ;
            foreach (string _line in lines)
            {
                string line = _line.Trim();
                if (!line.Contains(','))
                {
                    Console.Error.WriteLine("!!! Line did not contain comma for separation");
                    Console.Error.WriteLine("!!!!!! " + line);
                    continue; //Just go on to the next line.
                }
                string[] lineArray = line.Split(',');
                string answer = lineArray[1];
                string question = lineArray[0];
                questions.Add(question);
                answers.Add(answer);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("File could not be read");
        Console.WriteLine(e.Message);
    }
}

Of course if you want to read each line in separately, just check each line to make sure that it has any length after being trimmed (skip it if not) and that it contains a comma (log the error)

1

I suspect that there's a blank line (or at least a line without a comma) at the end of the file, and then this line: string annswer = lineArray[1]; is throwing an exception because you've hard-coded index 1 without first checking the size of the lineArray. Then the error is shown, but only after the questions and answers have been populated, so you also see those output to the console.

To avoid this, it's a general good practice is to ensure that an array index exists before checking it. Something like this might be helpful:

while ((line = reader.ReadLine()) != null)
{
    string[] lineArray = line.Split(',');

    // If this line doesn't contain a comma, then skip it
    if (lineArray.Length < 2) continue;

    string annswer = lineArray[1];
    string question = lineArray[0];
    questions.Add(question);
    answers.Add(annswer);
}

Alternatively, you could throw an exception:

// If this line doesn't contain a comma, throw an exception
if (lineArray.Length < 2)
{
    throw new FormatException($"This line does not contain a comma: {line}");
}

Additionally, you could simplify your code slightly by using the System.IO.File class to read the file:

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    try
    {
        foreach (var line in File.ReadLines(filename))
        {
            var lineArray = line.Split(',');

            // If this line doesn't contain a comma, skip it
            if (lineArray.Length < 2) continue;

            questions.Add(lineArray[0]);
            answers.Add(lineArray[1]);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine($"Error reading file: {e.Message}");
    }
}
0

This is one of technique to handle exception.
I've tried your code but it works well.
Apply my code it and look my comment.

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    string readText = ""; //for writing error at catch clause.
    try
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                readText = line;  //copy text line which is current.

                string[] lineArray = line.Split(',');
                string annswer = lineArray[1];
                string question = lineArray[0];
                questions.Add(question);
                answers.Add(annswer);
            }
        }
    }
    catch (Exception e)
    {
        //print error with problem text.
        Console.WriteLine("File could not be read from : {0}", readText);  
        Console.WriteLine(e.Message);
    }
}

Also, this is another,
Move to : Menu -> DEBUG -> Windows -> Exception settings. And then check "Common Language Runtime Exception". This will allow stop where occur problem. It doesn't matter that is in try~catch clause or not.
This is one of best way to find problem in loop statement.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.