我想要实现的是我有一个文件“附加课程”,它有一些格式错误和重复错误。当我将该文件导入到我的Course对象数组中时,它应该捕获这些错误。我坚持如何检查这些错误,并在导入时遇到问题。
有人可以看看这两个错误吗?
public void ImportCourses(string fileName, char Delim)
{
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
int index = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var array = line.Split(Delim);
Course C = new Course();
C.CourseCode = array[0];
C.Name = array[1];
C.Description = array[2];
C.NoOfEvaluations = int.Parse(array[3]);
courses[index++] = C;
//Console.WriteLine(C.GetInfo());
}
reader.Close();
stream.Close();
这些是我想要检查的例外情况:
我得到“索引越界数组”异常,我不知道从哪里开始异常。
这是我尝试导入的.txt:
答案 0 :(得分:1)
您应该检查array.Length以确保在尝试访问它们之前有4个元素。如果由于数据为空或数据没有4个分隔符而导致拆分失败,则该数组将不会是4个元素长并尝试按索引访问元素,这不会导致索引超出范围异常。
这是一个解决问题的潜在解决方案 - 尽管这有一个家庭作业的问题。
public class Course {
public string CourseCode { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int NoOfEvaluations { get; set; }
}
List<Course> courses = new List<Course>();
bool CourseAlreadyExists(Course course) {
foreach (Course c in courses) {
if (c.CourseCode == course.CourseCode) {
return true;
}
}
return false;
}
// Define other methods and classes here
public void ImportCourses(string fileName, char Delim) {
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
using (var reader = new StreamReader(stream)) {
int index = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var array = line.Split(Delim);
if (array.Length != 4)
{
throw new ApplicationException(String.Format("Invalid number of fields in record #{0}", index));
}
Course C = new Course();
C.CourseCode = array[0];
C.Name = array[1];
C.Description = array[2];
int evals;
if (!int.TryParse(array[3], out evals))
{
throw new ApplicationException(String.Format("Number of evaluations in record {0} is not in correct format.", index));
}
else
{
C.NoOfEvaluations = evals;
}
if (!CourseAlreadyExists(C))
{
courses[index++] = C;
}
else
{
throw new ApplicationException(String.Format("Course code in record {0} is in use", index));
}
}
}
}
}
}