另一个参差不齐的阵列问题:锯齿阵列和异常
当前在类中工作锯齿状数组而不是在Main()中。有了这个锯齿状的数组,我想根据自定义异常来测试我的用户输入。目前,当我运行程序时,它会创建阵列,直到我想填充阵列并测试该数据与我的异常的最后一点。尽管用户输入正确,异常仍在运行。我不确定错误是在我的异常中,还是错误是我的数组。
注:我知道这可能看起来有些复杂,但为了我正在做的事情,它必须保持这种方式。对不起:(
类
class StudentGrades
{
private char[][] grades;
private double totalGpa;
private int totalClasses;
private int semesters;
public StudentGrades()
{
totalClasses = 0;
SetSemesters(4);
grades = new char [semesters][];
}
public void InputSemesters()
{
int x;
int semestNum;
bool check;
do
{
check = false;
try
{
for (int r = 0; r < grades.Length; r++)
{
if (r == 0)
{
semestNum = 1;
}
else if (r == 1)
{
semestNum = 2;
}
else if (r == 2)
{
semestNum = 3;
}
else
{
semestNum = 4;
}
Console.Write("How many courses were taken semster {0}? ", semestNum);
x = int.Parse(Console.ReadLine());
CreateSemesters(r, x);
}
}
catch (System.FormatException e)
{
Console.WriteLine("Problem with input.\n{0}\nTry again.", e.Message);
check = true;
}
} while (check);
}
public void CreateSemesters(int sem, int numClasses)
{
grades[sem] = new char[numClasses];
totalClasses += numClasses;
}
public void EnterGrades()
{
int semestNum;
char letter;
bool check;
do
{
check = false;
try
{
for (int r = 0; r < grades.Length; r++)
{
if (r == 0)
{
semestNum = 1;
}
else if (r == 1)
{
semestNum = 2;
}
else if (r == 2)
{
semestNum = 3;
}
else
{
semestNum = 4;
}
for (int c = 0; c < grades[r].Length; c++)
{
Console.Write("Enter the letter grade for class {0} of semester {1}: ", c + 1, semestNum); //the array creation works up to this part. So I know the array is creating but not storing data.
letter = char.Parse(Console.ReadLine());
letter = grades[r][c];
CheckLetterGrade(letter);
}
}
}
catch (IncorrectLetterGradeException excepObj)
{
Console.Write("That is not an acceptable letter grade. Try Again. \n{0}", excepObj.Message);
Console.WriteLine();
check = true;
}
} while (check);
}
public void CheckLetterGrade(char G)
{
if (G != 'A' || G != 'B' || G != 'C' || G != 'D' || G != 'F')
{
IncorrectLetterGradeException excepObj = new IncorrectLetterGradeException("Not an acceptalbe letter grade of A-D or F");
throw excepObj;
}
}
的Main()
class UseStudentGrades
{
static void Main(string[] args)
{
StudentGrades student = new StudentGrades();
// testing array functionality below
student.InputSemesters();
student.EnterGrades();
}
}
异常
class IncorrectLetterGradeException :
System.ApplicationException
{
public IncorrectLetterGradeException(string exceptionType)
: base (exceptionType)
{
//empty body
}
}
更新1: 目前正在这一变化,看是否异常停止提示:
public void CheckLetterGrade(char G)
{
bool gradeMatch = (G == 'A' || G == 'B' || G == 'C' || G == 'D' || G == 'F');
if (!gradeMatch)
{
IncorrectLetterGradeException excepObj = new IncorrectLetterGradeException("Not an acceptalbe letter grade of A-D or F");
throw excepObj;
}
}
而且我得到这个问题:
Exception being thrown with correct user input
我敢肯定有可能缩减您的代码到最低限度为您的问题。谁应该读这一切? –
@ maf-soft这已被编辑删除那些不属于我的问题的项目。 – ZLackLuster