Dictionary.Count is not working as expected - c#

The following line of code is not working as expected: If there are two dictionary entries it prints "2, 2" instead of "1, 2"
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
It is not listing the dictionary count like this line ↓↓↓ of code above it in the other for-loop.
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
namespace Program
{
class Program
{
static void Main(string[] args)
{
string totalStudents = string.Empty;
while (!IsNumeric(totalStudents))
{
Console.WriteLine("How many students will you be grading?");
totalStudents = Console.ReadLine();
if (!IsNumeric(totalStudents))
{
Console.WriteLine(string.Empty);
Console.WriteLine("Error! Please enter numeric value.");
}
}
int studentCount = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
string totalScores = string.Empty;
while (!IsNumeric(totalScores))
{
Console.WriteLine("How many test scores will you enter for each student?");
totalScores = Console.ReadLine();
if (!IsNumeric(totalScores))
Console.WriteLine("Please enter a numeric value.");
}
int scoreCount = Convert.ToInt32(totalScores);
Dictionary<int, List<int>> studentMap = new Dictionary<int, List<int>>();
for (int students = 0; students < studentCount; students++)
{
List<int> studentScores = new List<int>();
for (int scores = 0; scores < scoreCount; scores++)
{
string scoreInput = string.Empty;
Console.WriteLine(string.Empty);
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
scoreInput = Console.ReadLine();
Console.WriteLine(string.Empty);
Console.WriteLine("--------------------");
int intScore = Convert.ToInt32(scoreInput);
studentScores.Add(intScore);
}
studentMap.Add(students, studentScores);
}
Console.WriteLine("The test results are as follows:");
Console.WriteLine(string.Empty);
for (int i = 0; i < studentMap.Count; i++)
{
List<int> studentScores = studentMap[i];
double scoreSum = studentScores.Sum();
double scoreNum = studentScores.Count();
double average = scoreSum / scoreNum;
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
}
Console.WriteLine();
Console.ReadLine();
}
static string GetLetterGrade(double average)
{
if (average >= 90)
{
return "A";
}
else if (average >= 80)
{
return "B";
}
else if (average >= 70)
{
return "C";
}
else if (average >= 60)
{
return "D";
}
else
{
return "F";
}
}
static double GetAverage(double sum, double count)
{
return sum / count;
}
static bool IsNumeric(string input)
{
int result;
return int.TryParse(input, out result);
}
}
}

You probably misunderstood the terms Dictionary<>.Count and index. Indexes start at 0 and Count property represents the number of items in the dictionary.
So, if you have 1 item in your Dictionary<>, it's index is 0 and Dictionary<>.Count is 1.

Related

c# how to fill an array with user input

I'm creating a lottery program that users can choose from a series of numbers between a particular range and the program then creates its own version of numbers and compares those user values against the program's random numbers which any matches that the program then finds are then displayed to the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assessment1.Lottery
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert 6 lottery numbers:");
int range = 100;
int minValue = 0;
int maxValue = 100;
int a = 0;
Random rnd = new Random();
int[] myArray = new int[6];
for ( int i=0; i < myArray.Length; i++ )
{
int randomNumber = rnd.Next(minValue, maxValue);
myArray[i] = randomNumber;
Console.WriteLine(randomNumber);
myArray[i] = int.Parse(Console.ReadLine());
Console.WriteLine(myArray[i]);
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out myArray[a]))
a++;
else
Console.WriteLine("invalid integer");
}
double arry = myArray.Average();
if(arry > 0)
Console.WriteLine("found");
else
Console.WriteLine("not found");
int BinarySearch(int[] array, int value, int low, int high)
{
if ( high >= low)
{
int mid = (low + high) / 2;
if (array[mid] == value) return mid;
if (array[mid] == value) return BinarySearch(array, value, low, mid - 1);
return BinarySearch(array, value, mid + 1, high);
}
return -1;
}
}
Console.ReadLine();
}
}
}
when I run the program it shows the following
Please insert 6 lottery numbers: 64
how can I fix this so that the array can be filled with user input
Here is a version of something I wrote a while back and modified to your parameters, if there are bugs please don't ask me to fix.
static void Main(string[] args)
{
int stop = 0;
int[] chosenNum = new int[6];
while (stop == 0)
{
Console.Clear();
string con = "";
Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
string numbers = Console.ReadLine();
string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
if (userNumbers.Count() < 6)
{
Console.WriteLine("You entered less than six numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (userNumbers.Count() > 6)
{
Console.WriteLine("You entered more than 6 numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (checkDup.Count() < 6)
{
Console.WriteLine("You entered duplicate numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (!isNumeric(userNumbers))
{
Console.WriteLine("You entered non-numeric value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (isInRange(userNumbers) < 6)
{
Console.WriteLine("You entered out of range value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else
{
var lowerBound = 1;
var upperBound = 100;
var random = new Random();
int[] randomNum = new int[6];
int count = 0;
foreach(string str in userNumbers){
var rNum = random.Next(lowerBound, upperBound);
randomNum[count] = rNum;
count++;
}
string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
Array.Sort(userNumbers);
Array.Sort(ourPicks);
//string[] ourpicks = { "1", "2" };//for testing
Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
string[] result = userNumbers.Intersect(ourPicks).ToArray();
if(result.Count() > 0)
{
Console.WriteLine("Matchs: {0}", string.Join(", ", result));
}
else
{
Console.WriteLine("Match's = 0");
}
stop = 1;
}
}
Console.ReadLine();
}
public static bool isNumeric(string[] num)
{
foreach (string str in num)
{
bool check = int.TryParse(str, out int test);
if (!check)
{
return false;
}
}
return true;
}
public static int isInRange(string[] num)
{
int count = 0;
foreach (string str in num)
{
int.TryParse(str, out int test);
if (test > 0 & test <= 100)
{
count++;
}
}
return count;
}

Console.Redline reading second line

I have a simple program that tells the user to input n amount of students, foreach student an x amount of money is allocated. At the end, the program divides x by n, meaning the total money is divided equally by the students.
The problem is that Console.Readline() is reading the second inputted value as see below.:
This means that the user has to enter the values two times, each time Console.Readline() is called, which is obviously wrong!
Code:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = 0;
try
{
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt(Console.ReadLine());
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt(string s)
{
int numericValue = 0;
bool done = false;
while (!done)
{
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 100)
Console.WriteLine("The input must be between 0 and 1000!");
else
done = true;
}
return numericValue;
}
You ReadLine twice:
noOfStudents = checkInputTypeInt(Console.ReadLine());
and in checkInputTypeInt method:
if (!int.TryParse(Console.ReadLine(), out numericValue))
You should either send only the string to method like this:
noOfStudents = checkInputTypeInt(Console.ReadLine());
and in your method just check that value like:
if (!int.TryParse(s, out numericValue))
in this case you should have the while loop in your main method.
or just use readline in the called method.
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt(); // and you should change your method to fit no arguments.
Edit: final codes:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = 0;
try
{
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt();
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt()
{
int numericValue = 0;
bool done = false;
while (!done)
{
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 100)
Console.WriteLine("The input must be between 0 and 1000!");
else
done = true;
}
return numericValue;
}
OR:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = -1;
try
{
Console.WriteLine("Please enter the number of students :");
do{
noOfStudents = checkInputTypeInt(Console.ReadLine());
}while(noOfStudents == -1);
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt(string s)
{
int numericValue = -1;
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 1000)
{Console.WriteLine("The input must be between 0 and 1000!");
numericValue = -1;
}
return numericValue;
}
Try to divide the noOfStudents and Console.ReadLine() like this:
int i = Convert.ToInt32(Console.ReadLine());
noOfStudents = i;

storing the result of a for loop into array and revrse it?

I want to store the result of the for loop in an array then reverse it.
Example:
When I run the program and enter 5 the answer will be
54321
I want it to be
12345
int num;
int index = 0;
Console.Write("Number: ");
num = int.Parse(Console.ReadLine());
for (int x = num; x > 0; x--)
{
index = Convert.ToInt32(index + x);
Console.Write(x);
}
Console.WriteLine("\nThe sum is: {0}", index);
Console.ReadLine();
How about this?
Console.Write("Number: ");
var num = int.Parse(Console.ReadLine()); // parse console input
var range = Enumerable.Range(1, num); //generate array of values from 1 to num
var str = String.Concat(range.Select(x => x.ToString())); //concatenate array of values
Console.WriteLine(str); // write string
var sum = range.Sum(); // get sum of array
Console.WriteLine("\nThe sum is: {0}", sum); // write sum
Console.ReadLine(); // pause
Ok, none of those responses really would do what you asked for, but I mut say your example is really misleading.
Try this:
public int[] ArrayAndReverse(int Number)
{
int[] data = new int[Number];
int index =
for (int x = Number; x > 0; x--)
{
index = Convert.ToInt32(index + x);
Console.Write(x);
}
return data.Reverse().ToArray();
}
now in your console code you can do:
Console.Write("Number: ");
num = int.Parse(Console.ReadLine());
int[] data = ArrayAndReverse(number);
foreach(int i in data)
Console.Write(i);
Also, not sure why your loop is already reversed, I suppose as I said this example is really misleading, else you can just use:
int[] data = Enum.Range(1, number).ToArray();
This will give you already the array in the right order.
Try this
For auto increment to total length
Use this
Console.WriteLine("Input length");
int length;
if (!int.TryParse(Console.ReadLine(), out length))
{
Console.WriteLine("Invalid number");
}
else
{
int[] array = new int[length];
for (int i = length; i > 0; i--)
{
array[length - i] = i;
}
Console.WriteLine("Array is");
foreach (var i in array)
{
Console.WriteLine(i);
}
Console.WriteLine("Reverse Array is");
foreach (var i in array.Reverse())
{
Console.WriteLine(i);
}
}
Console.ReadKey();
To take every number from user, try this
private static void Main(string[] args)
{
Console.WriteLine("Input length");
int length;
if (!int.TryParse(Console.ReadLine(), out length))
{
Console.WriteLine("Invalid number");
}
else
{
int[] array = new int[length];
for (int i = length; i > 0; i--)
{
int input;
Console.WriteLine("Input number");
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid number");
input = 0;
}
array[length - i] = input;
}
Console.WriteLine("Array is");
foreach (var i in array)
{
Console.WriteLine(i);
}
Console.WriteLine("Reverse Array is");
foreach (var i in array.Reverse())
{
Console.WriteLine(i);
}
}
Console.ReadKey();
}

C# mastermind game

In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)

Student class and Menu class not working

this is Students.cs
It is showing an error "NullReferenceException was unhandled" at line ---- Console.WriteLine("Student{0}: {1}, {2:P} {3}", i+1, stuList[i].studentName,stuList[i].studentPercentage, stuList[i].studentLetterGrade);
Can I get help finding the error with this two classes
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));
}
}
}
The above Students.cs is connected with 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();
}
}
}
This code is also connect with the following 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;
}
}
}
}
In your add student code you have a couple of problems
indexForNewStudent = 0;
This means you will always be overwriting the first student rather than adding a new one.
//Increment Student count
Student.SetStudentCount(indexForNewStudent + 2); //Add to index to account for new student
The +2 here means that your student count will be 1 greater than the number of students, meaning that the ListStudents function will then try to access a student that hasn't been added yet. It should be +1

Categories

Resources