这是Students.cs 它显示错误" NullReferenceException未处理" at line ---- Console.WriteLine(" Student {0}:{1},{2:P} {3}",i + 1,stuList [i] .studentName,stuList [i ] .studentPercentage,stuList [i] .studentLetterGrade);
我可以帮助找到这两个类的错误 private static int studentCount = 0;
// Instance variables go here
private string studentName;
private double studentPercentage;
private string studentLetterGrade;
private Grade test = new Grade(0);
private Grade hwQz = new Grade(700);
//Default Constructor Method
public Student()
{
}//end of Student Constructor method
public Student(string name)
{
//if(name.Length == 0)
SetStudentName("Jane Doe");
//else
//SetStudentName(name);
}//end of Overloaded Constructor method
public Student(string name, int percent, string letter)
{
SetStudentName(name);
SetStudentPercent(percent);
SetStudentLetter(letter);
}//end of Overloaded Constructor method
//Class Methods
// retrieve the student count
public static int GetStudentCount()
{
return studentCount;
}//end of GetStudentCount method
// set the student count
public static void SetStudentCount(int newStudentCount)
{
studentCount = newStudentCount;
}//end of SetStudentCount method
// list students
public static void ListStudents(Student[] stuList)
{
//Clear Screen
Console.Clear();
for (int i = 0; i < studentCount; i++)
{
Console.WriteLine("Student{0}: {1}, {2:P} {3}", i+1, stuList[i].studentName,stuList[i].studentPercentage, stuList[i].studentLetterGrade);
}
}
// Instance methods go here
// retrieve the Student name
public string GetStudentName()
{
return studentName;
}//end of GetStudentName method
// set the Student name
public void SetStudentName(string newName)
{
studentName = newName;
}//end of SetStudentName method
// retrieve the Student percent
public double GetStudentPercent()
{
return studentPercentage;
}//end of GetStudentPercent method
// set the Student address
public void SetStudentPercent(double newPercent)
{
studentPercentage = newPercent;
}//end of SetStudentPercent method
// retrieve the Student Letter
public string GetStudentLetter()
{
return studentLetterGrade;
}//end of GetStudentLetter method
// set the Student letter
public void SetStudentLetter(string newLetter)
{
studentLetterGrade = "A+";
}//end of SetStudentLetter method
public void EnterStudentScores()
{
test.EnterScores("Test");
hwQz.EnterScores("Homework & Quiz");
//Store the overall score in a temp variable
double gradePercent = ((50 * test.GetGradePercent()) + (50 * hwQz.GetGradePercent()));
//Using typecasting to force a double into an int data type
SetStudentPercent(gradePercent);
SetStudentLetter(test.GetLetterGrade(gradePercent));
}
}
}
上述Students.cs与Menu.cs
相关联 bool runApp = true;
Student[] students = new Student[35];
//Application loop
while (runApp)
{
Console.Clear();
Console.WriteLine("\n\tGrade Book Menu\n");
Console.WriteLine("\t1) Add Student");
Console.WriteLine("\t2) Enter Student Grades");
Console.WriteLine("\t3) List Student Grades");
Console.Write("\nEnter Selection or Press Escape to exit: ");
ConsoleKeyInfo key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
runApp = false;
}
else
{
switch (key.Key)
{
case ConsoleKey.NumPad1:
case ConsoleKey.D1:
//Get the current student count stored in the Student Class variable
int indexForNewStudent = Student.GetStudentCount();
indexForNewStudent = 0;
Console.Write("\nEnter Student Name: ");
//Instantiate a Student object and place it in the array of Student objects called student
students[indexForNewStudent] = new Student(Console.ReadLine()); //Call overloaded constructor
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
break;
case ConsoleKey.NumPad2:
case ConsoleKey.D2:
Console.WriteLine("\nEnter the Student Number. Use List Students to get Student Number.");
int studentNumber = 0; //Temporary variable to hold the student number to enter grades
//Test the entered string is a number and between 1 and 30
if ((int.TryParse(Console.ReadLine(), out studentNumber)) && (studentNumber >= 1) &&
(studentNumber <= 30))
{
//In the event a student has not been added this code will crash
if (Student.GetStudentCount() > 0) //Has a student been added?
students[studentNumber - 1].EnterStudentScores(); //Subtract 1 from enterd number for array index
else
Console.WriteLine("A student has not been added");
}
else
{
Console.WriteLine("Invalid Student Number. Enter a number from 1 to 30");
}
break;
case ConsoleKey.NumPad3:
case ConsoleKey.D3:
Student.ListStudents(students);
break;
default:
Console.WriteLine("Invalid Menu Selection");
break;
}
Console.Write("Press a key to return to Menu");
Console.ReadKey();
}
}
Console.Write("\nExiting Application. Press any key to close window... ");
Console.ReadKey();
}
}
}
此代码还连接以下Grade.cs
private double[] earnedScores = new double[30];
private double pointTotal = 0;
private int scoresEntered = 0;
public Grade()
{
}
public Grade(double total)
{
pointTotal = total;
}
public void SetPointTotal(int total)
{
pointTotal = (double)total; //using double to type cast an int into a double
}
public void SetPointTotal(double total) // Overloaded method for SetPointTotal
{
pointTotal = total;
}
public void EnterScores(string scoreType)
{
//Loop that lets the user enter up to 30 scores
//the loop ends after 30 entries or Q is pressed
do
{
Console.Clear(); //Clear screen
//scoreType is a string passed in that prints to the screen to help user know what scores are being entered
Console.WriteLine("{0} Scores", scoreType);
Console.WriteLine("Enter up to {0} scores or Q to quit.", earnedScores.Length);
Console.Write("Enter score{0}: ", scoresEntered + 1);
string input = Console.ReadLine();
//Validate user entered string stored in input.
//Return -2 if Q was pressed and -1 if the string is invalid
double inputNumber = ValidateScore(input);
if (inputNumber == -1)
{
Console.WriteLine("Invalid entry. Please enter a valid positive score.");
Console.ReadKey();
}
else if (inputNumber == -2)
{
break;
}
else
{
earnedScores[scoresEntered] = inputNumber;
scoresEntered++;
}
} while(scoresEntered < earnedScores.Length);
}
public void DisplayScore(string scoreType)
{
//scoreType is a string passed in that prints to the screen to help user know what scores are being displayed
Console.WriteLine("{0} Scores", scoreType);
//Loop thru the earnedScores array and print each element's value
for (int i = 0; i < scoresEntered; i++)
{
Console.WriteLine("Score{0}: {1}", i + 1, earnedScores[i]);
}
}
public double ValidateScore(string inText)
{
int dotCount = 0; //Variable to hold the count of decimals
char[] temp = inText.ToCharArray(); //char array to hold incoming string
if (inText.Length > 0) //text is not blank if length greater than zero
{
for (int i = 0; i < inText.Length; i++) //loop thru each character and test contents
{
if (temp[i] == '.') //is it a decimal
{
dotCount += 1; //dotCount++; does the same thing
if (dotCount > 1) //More than 1 decimal invalid
return -1;
}
else if (temp[i] == '-') //if Negative sign
{
if (i != 0) //If Negative is not 1st element of array then invalid
return -1;
}
else if (!char.IsNumber(temp[i])) //If character is not a number
{
if (temp[i] == 'Q' || temp[i] == 'q') //If Q or q then exit loop
{
return -2;
}
else //Any other letter invalid
{
return -1;
}
}
}
}
else
{
return -1; //Blank was entered
}
return Convert.ToDouble(inText);
}
public double GetGradePercent()
{
double totalEarnedPoints = 0; //Start with zero
//Add all elements of the array to total
for (int i = 0; i < scoresEntered; i++)
{
totalEarnedPoints += earnedScores[i];
}
//Return grade percentage by dividing earned points by total points
return totalEarnedPoints / pointTotal;
}
public string GetLetterGrade(double percentage)
{
//Incoming parameter will be in decimal format. Example 90% will be 0.90
percentage *= 100; //Multiply incoming percentage by 100 to move decimal point scaling number from 0 to 100
if (percentage >= 97.0)
{
return "A+";
}
else if ((percentage < 97) && (percentage >= 93))
{
return "A";
}
else if ((percentage < 93) && (percentage >= 90))
{
return "A-";
}
else if ((percentage < 90) && (percentage >= 87))
{
return "B+";
}
else if ((percentage < 87) && (percentage >= 83))
{
return "B";
}
else if ((percentage < 83) && (percentage >= 80))
{
return "B-";
}
else if ((percentage < 80) && (percentage >= 77))
{
return "C+";
}
else if ((percentage < 77) && (percentage >= 70))
{
return "C";
}
else if ((percentage < 70) && (percentage >= 60))
{
return "D";
}
else
{
return "E";
}
}
public void ClearScores()
{
scoresEntered = 0; //Clear number of scores previously entered
//Reset all elements of the array back to zero
for (int i = 0; i < earnedScores.Length; i++)
{
earnedScores[i] = 0.0;
}
}
}
}
答案 0 :(得分:0)
在您的添加学生代码中,您有几个问题
indexForNewStudent = 0;
这意味着你将永远覆盖第一个学生而不是添加新学生。
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
此处的+2表示您的学生人数将比学生人数大1,这意味着ListStudents功能将尝试访问尚未添加的学生。它应该是+1