另一個參差不齊的陣列問題:鋸齒陣列和異常
當前在類中工作鋸齒狀數組而不是在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