I am working on a project which involves creating two arrays and comparing the answers to determine a pass or fail state.
When I try to run my code I receive this error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ITEC exam.exe
Additional information: Index was outside the bounds of the array.
my code is as follows
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ITEC_exam
{
public partial class ITEC_exam : Form
{
public ITEC_exam()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string line;
int cnt = 0;
//List to hold question numbers of incorrect answers
List<int> incorrect = new List<int>();
//Array to store correct answers
string[] correctAnswers = { };
//Array to store answers
string[] answers = { };
//Read the files and store answers in arrays
System.IO.StreamReader correctFile = new System.IO.StreamReader("C:\\Users\\a_day\\Desktop\\Baker_Austin_c#_final\\ITECexam\\ITEC exam\\correctAnswers.txt");
System.IO.StreamReader answerFile = new System.IO.StreamReader("C:\\Users\\a_day\\Desktop\\Baker_Austin_c#_final\\ITECexam\\ITEC exam\\testResult.txt");
if ((line = correctFile.ReadLine()) != null)
correctAnswers = line.Split(' ');
if ((line = answerFile.ReadLine()) != null)
answers = line.Split(' ');
//Compare answers and compute the score
for (int i = 0; i < 21; i++)
{
if (String.Compare(correctAnswers[i], answers[i]) == 0)
cnt++;
else
incorrect.Add(i + 1);
}
//Print Result
if (cnt >= 15)
Console.WriteLine("\n\n Result: PASS");
else
Console.WriteLine("\n\n Result: FAIL");
//Printing score
Console.WriteLine("\n Total number of Correct Answers: " + cnt);
Console.WriteLine("\n Total number of Incorrect Answers: " + (20 - cnt));
Console.Write("\n Question numbers of incorrect answers: ");
//Printing incorrectly answered question numbers
foreach (int qno in incorrect)
Console.Write(" " + qno + " ");
//Closing Files
correctFile.Close();
answerFile.Close();
Console.WriteLine("\n\n Press any key to exit.");
Console.ReadKey();
}
}
}