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
Related
Below I am trying to create a method that returns a list filled with Five integers, based on userInput. I want to make methods to use inside that method.
Where would I create these methods in the class, to have scope of variables and then use them inside the main method that returns a list?
class UserLists
{
public static List<int> UserFiveList()
{
List<int> userList = new List<int>();
int userPick1 = 0;
int userPick2 = 0;
int userPick3 = 0;
int userPick4 = 0;
int userPick5 = 0;
// method that fills the list
void FillUserFiveList(int pick, int count)
{
do
{
Console.Write("Enter first number between 1-45 : ");
pick = int.Parse(Console.ReadLine());
if (userList.Contains(pick))
Console.WriteLine("You have to enter a unique number");
else if (pick >= 1 && pick <= 45)
{
Console.WriteLine("Adding your first number in the list...");
userList.Add(pick);
}
else
Console.WriteLine("You have to enter a number between 1-45");
} while (userList.Count < count);
}
//end of method
FillUserFiveList(userPick1, 1);
FillUserFiveList(userPick2, 2);
FillUserFiveList(userPick3, 3);
FillUserFiveList(userPick4, 4);
FillUserFiveList(userPick5, 5);
return userList;
}
public static List<int> UserOneList()
{
List<int> userOneList = new List<int>();
do
{
Console.Write("Enter your number between 1-20 : ");
int userPick1 = int.Parse(Console.ReadLine());
if (userPick1 >= 1 && userPick1 <= 20)
{
Console.WriteLine("Adding your only number in the list...");
userOneList.Add(userPick1);
}
else
Console.WriteLine("You have to enter a number between 1-20");
} while (userOneList.Count < 1);
return userOneList;
}
}
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.
Create:
This class defines an Employee.
Member variables: ID (int), name (string), salary (double)
Member Methods: Constructors, input/output methods that perform I/O for an employee
Create:
This class defines an array of Employees
Member variables: An array of Employee, SIZE (int), currentSize (int)
Member Methods: Constructors, input/output methods, search/insert/delete/update methods.
Not sure exactly how to store 3 Employee variables inside a single array index.
Updated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Employee
{
protected int id;
protected string name;
protected double salary;
public Employee()
{
}
public Employee(int _id, string nm, double sal)
{
id = _id;
name = nm;
salary = sal;
}
public void PrintEmployee()
{
Console.WriteLine("id: {0}", id);
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Salary: {0}", salary);
}
}
class EmployeeArray : Employee
{
private Employee[] a;
private int currSize;
private const int SIZE = 100;
public EmployeeArray()
: base()
{
}
public EmployeeArray(int s, int _id, string nm, double sal)
: base(_id, nm, sal)
{
a = new Employee[SIZE];
if (s > SIZE)
Console.WriteLine("Array size is overflow!");
else if (s == SIZE)
Console.WriteLine("Array is full.");
else
currSize = s;
}
public void Input()
{
a = new Employee[3];
for (int i = 0; i < currSize; i++)
{
a[i] = new Employee(id, name, salary);
}
}
public void Output()
{
Console.WriteLine("Array is: ");
foreach (Employee x in a)
Console.WriteLine("a[{0}]= {1}", name, x);
}
public int Search(int key)
{
for (int i = 0; i < currSize; i++)
{
//if (a[i] == key)
// return i;
}
return -1;
}
public void Insert()
{
if (currSize == SIZE)
{
Console.Write("Array is full! ");
return;
}
Console.WriteLine("Enter a number to insert: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter the index to where it is to insert: ");
int pos = int.Parse(Console.ReadLine());
for (int i = currSize; i > pos; i--)
a[i] = a[i - 1];
//a[pos] = y;
currSize++;
}
public void Delete()
{
if (currSize == 0)
{
Console.WriteLine("Array is empty! ");
return;
}
Console.Write("Delete by value (1) or by index (2): ");
int key = int.Parse(Console.ReadLine());
int pos = -1;
if (key == 1)
{
Console.WriteLine("Enter the number to delete: ");
int d = int.Parse(Console.ReadLine());
pos = Search(d);
while (pos == -1)
{
Console.WriteLine("The number does not exist, enter again: ");
d = int.Parse(Console.ReadLine());
pos = Search(d);
}
}
else if (key == 2)
{
Console.WriteLine("Enter the index to delete from: ");
pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos > currSize)
{
Console.WriteLine("The index is out of range, enter again: ");
pos = int.Parse(Console.ReadLine());
}
}
else
return;
for (int i = pos; i < currSize; i++)
a[i] = a[i + 1];
currSize--;
if (currSize <= 0)
Console.Write("Array is empty! ");
}
public void Update()
{
Console.WriteLine("Enter the index where to update: ");
int pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos >= currSize)
{
Console.WriteLine("The index you entered is not valid, enter again: ");
pos = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the new value: ");
int x = int.Parse(Console.ReadLine());
//a[pos] = x;
Console.Write("Update complete! ");
}
}
class Program
{
//static char ShowMenu()
//{
// Console.WriteLine("\nEnter the letter of operation: \n(o)Print, (s)Search, (i)Insertion, (d)Deletion, (u)Update, (e)Exit\n");
// return char.Parse(Console.ReadLine());
//}
static void Main(string[] args)
{
//char sel = ' ';
Console.Write("Enter number of Employees; ");
int i = 0;
int s = int.Parse(Console.ReadLine());
while ( i < s )
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Enter id: ");
int _id = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter Name: ");
string nm = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Enter Salary: ");
double sal = int.Parse(Console.ReadLine());
EmployeeArray arr = new EmployeeArray(s, _id, nm, sal);
i++;
}
}
}
}
This reads like homework but I'll help you out.
You create your employee class with it's three members and methods.
then you create an array of employee objects.
//How Many employee objects do you need. Let's assume 10 for example
int NUM = 10;
Employee[] employees = new Employee[NUM]; // Declare an An array of employee's of length 10 (zero indexed from 0 - 9)
//Assuming you have made Getters and Setters
//Then if you need to access an employee object's member(s)
employees[0].getId(); //get the first employee's id
employees[0].getName(); //get the first employee's name
employees[0].getSalary(); //get the first employee's name
// Or set them like
employees[4].setId(12); //set the fifth employee's id to 12
employees[4].setName("Joe Bloggs"); //set the fifth employee's name to Joe Bloggs
employees[4].setSalary("30000"); //set the fifth employee's salary to 30000
MSDN C# Arrays
MSDN Classes
There are lots of problems with the code you posted. I'm just going to highlight a few issues, especially since this implementing arrays sounds a lot like computer science homework.
EmployeeArray inherits from Employee. Think about the meaning of public and private keywords and base classes.
Your functions all do more than one thing. This really complicates your code, and is going to result in bugs. Focus on straightforward code that does one thing and communicates what it does.
Users could crash your program in several places by entering something other than a number.
Lastly, to directly answer your question, you can access arrays through an index. You can't store three separate Employee objects in the same index. You've accessed array objects in other parts of your code, so it seems like you understand that you can store different values in different indexes.
This code verifies whether an ISBN is valid. For nine-digit inputs, I'd like to form a valid ISBN by calculating and appending the check digit. For inputs less than nine digits, I'd like it to return the error message "Please enter a correct number". How should I go about this?
public class isbn
{ //attributes
private string isbnNum;
//method
public string GetIsbn()
{
return this.isbnNum;
}
//constructor
public isbn()
{
Console.Write("Enter Your ISBN Number: ");
this.isbnNum = Console.ReadLine();
}//end default constructor
//method
public string displayISBN()
{
return this.GetIsbn();
}
public static void Main(string[] args)
{
//create a new instance of the ISBN/book class
isbn myFavoriteBook = new isbn();
//contains the method for checking validity
bool isValid = CheckDigit.CheckIsbn(myFavoriteBook.GetIsbn());
//print out the results of the validity.
Console.WriteLine(string.Format("Your book {0} a valid ISBN",
isValid ? "has" : "doesn't have"));
Console.ReadLine();
}
public static class CheckDigit
{ // attributes
public static string NormalizeIsbn(string isbn)
{
return isbn.Replace("-", "").Replace(" ", "");
}
public static bool CheckIsbn(string isbn) // formula to check ISBN's validity
{
if (isbn == null)
return false;
isbn = NormalizeIsbn (isbn);
if (isbn.Length != 10)
return false;
int result;
for (int i = 0; i < 9; i++)
if (!int.TryParse(isbn[i].ToString(), out result))
return false;
int sum = 0;
for (int i = 0; i < 9; i++)
sum += (i + 1) * int.Parse(isbn[i].ToString());
int remainder = sum % 11;
if (remainder == 10)
return isbn[9] == 'X';
else
return isbn[9] == (char)('0' + remainder);
}
Just change it to append the last character rather than checking that it's present. The above could be cleaned up a bit, but just changing it as required results in:
public static string MakeIsbn(string isbn) // string must have 9 digits
{
if (isbn == null)
throw new ArgumentNullException();
isbn = NormalizeIsbn (isbn);
if (isbn.Length != 9)
throw new ArgumentException();
int result;
for (int i = 0; i != 9; i++)
if (!int.TryParse(isbn[i].ToString(), out result))
throw new ArgumentException()
int sum = 0;
for (int i = 0; i != 9; i++)
sum += (i + 1) * int.Parse(isbn[i].ToString());
int remainder = sum % 11;
if (remainder == 10)
return isbn + 'X';
else
return isbn + (char)('0' + remainder);
}
I have a logical error. I provided the following as input:
the salary is 30000
the child nĀ° is 9
So the the net salary will be:
the family bonus + salary - tax
(750) + (30000) - (3000)
but my program count them as
(1500) + (30000) + (6000)
My program doubled (accumulated) the family bonus and the tax. Can anyone explain why?
class Program
{
static void Main(string[] args)
{
Employee e = new Employee();
e.ReadEmployee();
e.PrintEmployee();
}
}
class Employee
{
private string n;
private int byear;
private double sal;
private bool gen;
private bool mar;
private int child;
public static double tax = 0;
public static double familybonus = 0;
public string Ename
{
get { return this.n; }
set
{
this.n = value;
}
}
public int Birthyear
{
get { return this.byear; }
set
{
if (value >= 1970 && value <= 1990) this.byear = value;
else this.byear = 0;
}
}
public double Salary
{
get { return this.sal; }
set
{
if (value >= 5000 && value <= 50000) this.sal = value;
else this.sal = 0;
}
}
public bool Gender
{
get { return this.gen; }
set { this.gen = value; }
}
public bool Married
{
get { return this.mar; }
set { this.mar = value; }
}
public int NChildren
{
get { return this.child; }
set
{
if (value >= 0 && value <= 12) this.child = value;
else this.child = 0;
}
}
public double getAge()
{
return 2008 - this.Birthyear;
}
public double getNet()
{
double net = getFamilyBonus() + this.Salary - getTax();
return net;
}
public double getFamilyBonus()
{
if (this.Married == true)
familybonus += 300;
if (this.NChildren == 1) familybonus += 200;
else if (this.NChildren == 2) familybonus += 350;
else if (this.NChildren >= 3) familybonus += 450;
return familybonus;
}
public double getTax()
{
if (Salary < 10000)
tax = 0;
if (Salary <= 10000 && Salary >= 20000)
tax += Salary * 0.05;
else tax += Salary * 0.1;
return tax;
}
public void ReadEmployee()
{
Console.Write("Enter Employee Name: ");
Ename = Console.ReadLine();
Console.Write("Enter Employee birth date: ");
Birthyear = int.Parse(Console.ReadLine());
while (Birthyear < 1970 || Birthyear > 1990)
{
Console.WriteLine("Invalid Birthyear!");
Console.Write("Enter Employee Birth date: ");
Birthyear = int.Parse(Console.ReadLine());
}
string g = null;
while (g != "M" && g != "m" && g != "F" && g != "f")
{
Console.Write("Enter Employee Gender (M/F)");
g = Convert.ToString(Console.ReadLine());
}
if (g == "M" || g == "m")
Gender = true;
else
Gender = false;
Console.Write("Enter Employee Salary: ");
Salary = Double.Parse(Console.ReadLine());
while (Salary < 5000 || Salary > 50000)
{
Console.WriteLine("Invalid Salary!");
Console.Write("Enter Employee Salary: ");
Salary = int.Parse(Console.ReadLine());
}
string m = null;
while (m != "true" && m != "True" && m != "false" && m != "False")
{
Console.Write("Married (true/false)");
m = Console.ReadLine();
}
if (m == "true")
this.Married = true;
else
this.Married = false;
Console.Write("Enter Employee Children count: ");
NChildren = int.Parse(Console.ReadLine());
while (NChildren < 0 || NChildren > 12)
{
Console.WriteLine("Invalid NChildren!");
Console.Write("Enter Employee Children count: ");
NChildren = int.Parse(Console.ReadLine());
}
}
public void PrintEmployee()
{
Console.Write("Hello ");
{
if (Gender == true)
Console.Write("Mr. ");
else
Console.Write("Mrs. ");
Console.WriteLine(Ename);
}
Console.WriteLine("You are {0} years old", getAge());
Console.WriteLine("Salary= {0}", Salary);
Console.WriteLine("Tax= {0}", getTax());
Console.WriteLine("Family bonus= {0}", getFamilyBonus());
Console.WriteLine("Net= {0}", getNet());
}
}
I took the existing code, and hard-wired the inputs (rather than using Console.ReadLine()), I get:
You are 28 years old Salary= 30000
Tax= 3000 Family bonus= 750 Net= 25500
The main problem seems to be not initializing values - i.e. treating fields as variables:
public double getTax()
{
if (Salary < 10000)
tax = 0;
if (Salary <= 10000 && Salary >= 20000)
tax += Salary * 0.05;
else tax += Salary * 0.1;
return tax;
}
OK - and what does tax start at if Salary >= 10000, etc. Likewise familyBouns in getFamilyBonus. By the way, how can Salary be both <= 10000 and >= 20000?
To illustrate, I've changed the output to:
Console.WriteLine("Tax= {0}", getTax());
Console.WriteLine("Tax= {0}", getTax());
Console.WriteLine("Tax= {0}", getTax());
Which shows:
Tax= 3000 Tax= 6000 Tax= 9000
My advice would be: don't store calculated values unless you know the math is so complex that it is worth it. Just calculate them as needed (no field at all).
Another problem seems to lie in the fact that you don't initialize familybonus when you say familybonus += 300. So everytime you call GetFamilybonus it's added to the previous result. You call it twice in the PrintEmployee function, once directly and once indirectly by calling getNet;