C# class not responding - c#

I am making a program that calculates an employee's wages based on their hours and pay rate. However, when I try to use the method I created in another class:
public void GrossPay(int i)
{
double GrossPay = 0.0;
GrossPay = Hours[i] * PayRate[i];
Wages[i] = GrossPay;
}
trying to use it in my main program:
public static void Payroll()
{
int employeeID = 0;
int hours = 0;
double payRate = 0.0;
double wages = 0.0;
Payroll payroll = new Payroll(employeeID, hours, payRate, wages);
for (int i = 0; i < payroll.EmployeeID.Length; i++)
{
Console.WriteLine("Employee ID: {0}", payroll.EmployeeID[i]);
Console.WriteLine("How many hours does employee {0} work?", payroll.EmployeeID[i]);
string h = Console.ReadLine();
payroll.Hours[i] = Convert.ToInt32(h);
Console.WriteLine("What is the hourly wage for employee {0}?");
string w = Console.ReadLine();
payroll.PayRate[i] = Convert.ToInt32(w);
Console.WriteLine("Employee ID: {0} \nGross Pay: {1}", payroll.EmployeeID[i], payroll.Wages[i]);
Console.ReadLine();
}
}
Gross Pay returns 0, no matter what. Please help!

You never called the method that you've built; You should invoke it before you read from the Wages property.
// ...
payroll.PayRate[i] = Convert.ToInt32(w);
payroll.GrossPay(i);
Console.WriteLine("Employee ID: {0} \nGross Pay: {1}", payroll.EmployeeID[i], payroll.Wages[i]);
// ...
This will fix your problem, but I recommend that you give object oriented paradigm a shot. I recommend that you create an Employee class, which will have properties such as Id, PayRate, Hours and a property Wages which may look like this:
public double Wages
{
get
{
return PayRate * Hours;
}
}
Then, Payroll class may hold a sequence of employees: List<Employee> Employees;

Related

Why is my output equaling zero? (student)

I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:
EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)
Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project_3_rev
{
class Program
{
const int DEPARTMENTS = 7;
const int FIELDS = 4;
static void Main(string[] args)
{
FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string input = "";
string[] fields = new string[FIELDS];
string employee = "";
int department = 0;
double salary = 0.00;
int hours = 0;
double totalSalary = 0.00;
int totalHours = 0;
double[] grossPayArray = new double[DEPARTMENTS];
input = inFile.ReadLine();
while(input != null)
{
fields = input.Split(',');
checkEmployee(input, fields, employee);
checkDepartment(input, fields, department);
for(int x = 1; x <= DEPARTMENTS; x++)
{
totalSalary = 0.00;
totalHours = 0;
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
grossPayArray[x - 1] = totalSalary * totalHours;
}
}
input = inFile.ReadLine();
}
displayOutput(grossPayArray);
}
static void checkEmployee(string inp, string[] fieldsArray, string emp)
{
if(fieldsArray[0] == null)
Console.WriteLine("An Employee ID is invalid.");
}
static void checkDepartment(string inp, string[] fieldsArray, int dept)
{
if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
{
Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
}
}
static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
totSal = totSal * sal;
else
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
{
if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
totHrs = totHrs * hrs;
else
Console.WriteLine("Hours field is invalid: " + fieldsArray[3]);
}
static void displayOutput(double[] grossArray)
{
for(int x = 1; x <= DEPARTMENTS; x++)
{
Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
}
}
}
}
My output:
Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0
Why are the Gross Pays equaling zero?
Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.
In these two lines of code:
totalSalary = 0.00;
totalHours = 0;
you set the values to zero. Multiplying them by anything later, will still be zero. You need to make sure you either update these fields with the correct values before multiplying, or at the very least set them to 1.
The problem of your code is this kind of function:
static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
totSal = totSal * sal;
else
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
Is similar to this kind of function:
function Increase(int number) {
number = number + 1;
}
var number = 5;
Increase(number);
Console.WriteLine(number);
What you get is 5, instead of your expectation, 6.
In C#, it's called "passed by value". The value is passed into the function, and no modification is affected to the outside variable. In your case, toSalary will remain 0.
YOu need to change to ref double toSalary to use "pass by reference".
Other thing you need to practice is debugging technique:
Put break point.
Print the value to check.
Write unit tests to verify your methods.
Looks like you are multiplying 'grossPayArray[x - 1] = totalSalary * totalHours;' correctly, but it appears you are not updating totalSalary or totalHours from the initial value of 0.
You will need to read the file.
Split the values.
Update the variables, from zero.
Perform your function, in this case, multipling.
Hope that helps
The problem is here:
for(int x = 1; x <= DEPARTMENTS; x++)
{
totalSalary = 0.00;
totalHours = 0;
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
grossPayArray[x - 1] = totalSalary * totalHours;
}
}
Notice that you never change the variables totalSalary and totalHours.
What I suggest you do is redefine your functions to only validate the input salary:
static void validateSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
// you might want to rewrite this
if !((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
This way, the function actually only validates the salary, as it was named. See: Single Responsibility Principle
Then set your total salary within the loop itself:
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
totalSalary *= salary;
totalHours += hours;
grossPayArray[x - 1] = totalSalary * totalHours;
}
EDIT: Of course, this still has the problem that salary doesn't change within the loop.
This type of question might be better in the Code Review section of StackExchange.
Nonetheless, for your reference later in the year, here's an example solution using classes and LINQ:
To run:
var app = new App_DepartmentPay();
app.Run();
Output:
using System;
using System.IO;
using System.Linq;
namespace StackOverflow
{
public class App_DepartmentPay
{
public void Run()
{
var lines = File.ReadAllLines(#"d:\temp\payments.txt");
var payStubs = lines.Select(l => new PayStub(l)).ToList();
var departmentTotals = payStubs.GroupBy(p => p.Department).Select(g => new DepartmentTotal(g.Key, g.Sum(w => w.Pay))).ToList();
departmentTotals.ForEach(t => Console.WriteLine(t.ToString()));
}
}
public class PayStub
{
public string EmployeeId { get; private set; }
public int Department { get; private set; }
public decimal HourlyWage { get; private set; }
public decimal HoursWorked { get; private set; }
public decimal Pay
{
get
{
return HourlyWage * HoursWorked;
}
}
public PayStub(string payLine)
{
var contents = payLine.Split(',');
EmployeeId = contents[0];
Department = int.Parse(contents[1]);
HourlyWage = decimal.Parse(contents[2]);
HoursWorked = decimal.Parse(contents[3]);
}
}
public class DepartmentTotal
{
public int Department { get; set; }
public decimal TotalPay { get; set; }
public DepartmentTotal(int department, decimal pay)
{
Department = department;
TotalPay = pay;
}
public override string ToString()
{
return $"Department: {Department} \tGross Pay: {TotalPay}";
}
}
}

loops for prevent duplicate input to an array [duplicate]

This question already has answers here:
Using .Contains() on a property in a list
(8 answers)
Closed 5 years ago.
So, for our c# class we have to create an array of 5 objects, that have 4 properties
an int for job number
a string for job name
a string for job description
a double for expected hours of the job.
I need in my loop a way to prevent the user from entering a duplicate job number: here is my code so far. This code works, but will allow duplicate job numbers;
namespace JobDemo2
{
class Program
{
static void Main(string[] args)
{
Job[] jobbies = new Job[5];
int x;
int jobNum;
string customerName;
string description;
double hours;
const double RATE = 45.00;
for (x = 0; x < jobbies.Length; ++x)// creates array
{
GetJobData(out jobNum, out customerName, out description, out hours, jobbies);
jobbies[x] = new Job(jobNum, customerName, description, hours);
}
//Array.Sort(jobbies);
Console.WriteLine("The jobs, sorted, are: ");
for (x = 0; x < jobbies.Length; ++x) // prints the array values
{
DisplayJobs(jobbies[x]);
}
double totalRevenue = (jobbies[0].Hours + jobbies[1].Hours +
jobbies[2].Hours + jobbies[3].Hours + jobbies[4].Hours) * RATE;
Console.WriteLine();
Console.WriteLine("The total revenue projected is {0}", totalRevenue);
Console.ReadKey();
}
static void GetJobData(out int jobNum,
out string customerName, out string description, out double hours,
Job[] jobbies)
{
string inString;
Console.Write("Please enter a job number >> ");
inString = Console.ReadLine();
int.TryParse(inString, out jobNum);
Console.Write("Please enter the customer's name for this job >> ");
customerName = Console.ReadLine();
Console.Write("Please enter the job's description >> ");
description = Console.ReadLine();
Console.Write("Please enter the projected hours for the job >> ");
inString = Console.ReadLine();
double.TryParse(inString, out hours);
Console.WriteLine();
}
static void DisplayJobs(Job jobbies)
{
Console.WriteLine("{0, 5} {1, -10} {2, 6} {3, 8}",
jobbies.JobNumber, jobbies.Customer, jobbies.Description, jobbies.Hours);
}
}
class Job //object
{
private double hours;
private double price;
public const double RATE = 45.00;
public Job(int num, string cust, string desc, double hrs)
{
JobNumber = num;
Customer = cust;
Description = desc;
Hours = hrs;
}
public int JobNumber { get; set; }
public string Customer { get; set; }
public string Description { get; set; }
public double Hours
{
get
{
return hours;
}
set
{
hours = value;
price = hours * RATE;
}
}
public double Price
{
get
{
return price;
}
}
public override string ToString()
{
return (GetType() + " " + JobNumber + " " + Customer + " " +
Description + " " + Hours + " hours #" + RATE.ToString("C") +
" per hour. Total price is " + Price.ToString("C"));
}
public override bool Equals(Object e)
{
bool equal;
Job temp = (Job)e;
if (JobNumber == temp.JobNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return JobNumber;
}
}
}
the teacher is suggesting to the class that we ad another for loop here that compares the objects. What would that for loop look like?
Here is her email:
help for the looping create a boolean variable.
for loop through your array to ask the user to enter info and set your bool variable to true.
another for loop inside to call the equals method in the class that will compare the job just entered to each object in In the array. This is where most are messing up because you must compare objects to objects and not an interger for job number to an entire object. if the objects equal set the bool to false.
while the bool is false you want to tell them they entered a wrong number and to enter again. Set the bool to true in here and go the same for loop to compare again. as long as the number stays false the user will be stuck in this while loop. when they enter a correct number it will break out.
This is homework, so I'll only give you some pointers:
Don't hand in the array (jobbies) storing the jobs to GetJobData. This method should have only one concern: getting job data. Figuring out if the data has a duplicate Id is not it's concern.
Write a helper method that checks for duplicates. What does it need? It needs all previous jobs, how many there are, and the new job it needs to validate. The following signature looks about right:
private static bool CheckIfNewJobIsValid(Job newJob,
Job[] jobs,
int jobsValidatedCount)
What does this method have to do? Well, it only needs to loop through the first jobsValidatedCount jobs in jobs and check if newJob equals any of them. If it does, bail out returning false. If the loop finishes then you can return true, no match was found.
jobsValidatedCount doesn't need to be a new counter, maybe some other already existing variable in the code can give you that info already.
Good luck!
P.D. Because this was already handed down by your teacher, I'll fix up the Equals method just a little:
public override bool Equals(Object e)
{
bool equal = false;
Job temp = e as Job;
if (Job != null && JobNumber == temp.JobNumber)
{
equal = true;
}
return equal;
}
P.D. As Alexei Levenkov points out in comments, using Equals ony for JobNumber comparisson seems a bad idea. Are any two jobs with the same JobNumber really equal regardless of the value of all other properties? That could be confusing to say the least. A better approach would be to directly check JobNumber inside CheckIfNewJobIsValid and not use Equals but I guess its use is due to academic reasons.

2d array calculator in C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having a little trouble making a calculator. I can't seem to be able to enter the item name, only numbers. Also, it only takes the last price and quantity and multiplies them not the entirety. Update: I made the changes to the code about the subtotal and break,but it keeps telling me
Error CS0029
Cannot implicitly convert type 'string' to 'string[,]'
Error CS0019
Operator '==' cannot be applied to operandstype'string[,]' and 'int'
I can't seem to make it work or add a list to the end. Any help would be appreciated.
int[] array;
string[,] name = new string[100, 4];
decimal counter;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
decimal quantity;
subtotal = 0;
counter = 0;
array = new int[5];
while (counter <= 10)
{
Console.Write("Item{0}", counter + 1);
Console.Write(" Enter item name: ");
name = Console.ReadLine();
if (name == 0)
break;
Console.Write(" Enter price: ");
price = Convert.ToDecimal(Console.ReadLine());
counter = counter + 1;
Console.Write(" Enter quantity: ");
quantity= Convert.ToInt32(Console.ReadLine());
subtotal += price * quantity;
}
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", counter);
Console.WriteLine("Subtotal is {0}", subtotal);
tax = subtotal * 0.065M;
Console.WriteLine("Tax is {0}", tax);
total = tax + subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
I also know that I need to have for ( int counter = 0; counter < array.Length; counter++ ) in the code too, but it won't work. Thank-you for your time and help in advance.
You're trying to convert name to a number:
name = Convert.ToInt32(Console.ReadLine());
if (name == 0)
break;
Try removing "Convert.ToInt" like this:
name = Console.ReadLine();
Maybe this program will help you in learning C#. But you have to promise to try to understand how and why it works. Also, use the debugger to step in order to see how each statement affects the values stored in the variables.
class Program
{
static void Main(string[] args)
{
const int max_count = 10;
string[] name = new string[max_count];
int[] quantity = new int[max_count];
decimal[] price = new decimal[max_count];
decimal subtotal = 0;
int count = 0;
// Enter Values
for(int i = 0; i<max_count; i++)
{
Console.Write("Item{0}", i+1);
Console.Write("\tEnter Item Name: ");
name[i]=Console.ReadLine();
if(name[i].Length==0)
{
break;
}
Console.Write("\tEnter Price: ");
price[i]=decimal.Parse(Console.ReadLine());
Console.Write("\tEnter Quantity: ");
quantity[i]=int.Parse(Console.ReadLine());
subtotal+=quantity[i]*price[i];
count+=1;
}
// Display Summary
Console.WriteLine("-------------------");
Console.WriteLine("\nNumber of Items:{0}", count);
Console.WriteLine("Subtotal is {0}", subtotal);
decimal tax=subtotal*0.065M;
Console.WriteLine("Tax is {0}", tax);
decimal total=tax+subtotal;
Console.WriteLine("Total is {0}", total);
Console.WriteLine("Thanks for shopping! Please come again.");
Console.Read();
}
}
What you have here is a structure (the Program) of arrays. There are three arrays each storing a different type of value (string, int ,decimal). Later you should learn to make a single array of a structure, each containing multiple values.
public class Item
{
public string name;
public decimal price;
public int quantity;
}
// Usage
var cart = new List<Item>();

Method being run through twice when it should only run once

class Myclass
{
public string Driver1()
{
string a = "";
Console.Write("Please enter drivers name: ");
a = Console.ReadLine();
return a;
}
public int numberOfTrips()
{
int a = 0;
{
Console.Write("Enter the number of trips: ");
a = Convert.ToInt32(Console.ReadLine());
}
return a;
}
public List<float> Payments()
{
List<float> a = new List<float>();
float input;
for (int i = 0; i<numberOfTrips(); i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
}
class Program
{
static void Main(string[] args)
{
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments().Sum();
Console.WriteLine("\nDriver: {0}\n" + "Number of trips: {1}\n" + "Total payment: {2}\n", name, trip, total);
}
}
The issue i am having is that the "public int numberOfTrips()" method is running twice before it gets to the method containing the for loop. I think this is to do with the fact i am using it within the for loop to specify when the loop should stop. I am guessing i have done this wrong so how would i correct this? I need the user to be able to set the how many times it will ask for payment.
Any help is appreciated.
Just pass the number from numberOfTrips as a parameter to Payments:
public List<float> Payments(int tripCount)
{
List<float> a = new List<float>();
float input;
for (int i = 0; i < tripCount; i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
In your Main method:
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments(trip).Sum();
Instead of calling numberOfTrips() in Main() as well as in Payments() you might try creating an instance variable or static variable in MyClass. Then you can fetch the number of trips from that variable after all payments are calculated.
That is correct. The first time it runs is in Main to set the 'trip' variable. The second time it runs is in Payments, inside the for loop declaration.

Converting Char to Uppercase From User Inputted Data

I am trying to create a program for a hotel where the user is to enter a character (either S, D, or L) and that is supposed to correspond with a code further down the line. I need help converting the user input (no matter what way they enter it) to be converted to uppercase so I can then use an if statement to do what I need to do.
My code so far is the following:
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
**^Right Her is Where I Want To Convert To Uppercase^**
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}
public static double RoomCharge(int NumDays, char RoomType)
{
double Charge = 0;
if (RoomType =='S')
Charge = NumDays * 80.00;
if (RoomType =='D')
Charge= NumDays * 125.00;
if (RoomType =='L')
Charge = NumDays * 160.00;
Charge = Charge * (double)NumDays;
Charge = Charge * 1.13;
return Charge;
}
Try default ToUpper method.
roomtype = Char.ToUpper(roomtype);
Go through this http://msdn.microsoft.com/en-us/library/7d723h14%28v=vs.110%29.aspx
roomtype = Char.ToUpper(roomtype);
public static void Main()
{
int numdays;
double total = 0.0;
char roomtype, Continue;
Console.WriteLine("Welcome to checkout. We hope you enjoyed your stay!");
do
{
Console.Write("Please enter the number of days you stayed: ");
numdays = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("S = Single, D = Double, L = Luxery");
Console.Write("Please enter the type of room you stayed in: ");
roomtype = Convert.ToChar(Console.ReadLine());
roomtype = Char.ToUpper(roomtype);
total = RoomCharge(numdays,roomtype);
Console.WriteLine("Thank you for staying at our motel. Your total is: {0}", total);
Console.Write("Do you want to process another payment? Y/N? : ");
Continue = Convert.ToChar(Console.ReadLine());
} while (Continue != 'N');
Console.WriteLine("Press any key to end");
Console.ReadKey();
}

Categories