Hourly Pay Calc - c#

The Task:
Create a hourly pay calculator which is simple to use but effective.
private double amount4Hours = 4;
private double amount8Hours = 8;
private double amount10Hours = 10;
private void btnSubtotal_Click(object sender, EventArgs e)
{
double answer;
// 45 min break removal
double break45 = 0.75;
double outputValue = 0;
bool isNumber = true;
//true false statement for error checking
isNumber = double.TryParse(text4Hours.Text, out outputValue);
isNumber = double.TryParse(text8Hours.Text, out outputValue);
isNumber = double.TryParse(text10Hours.Text, out outputValue);
if (!isNumber)
{
//error checking for blank text boxes
MessageBox.Show("Enter a number from 0-9");
}
else
{
//calculates total amount of hours after breaks have been removed
amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
amount8Hours = amount8Hours * double.Parse(text8Hours.Text) -
break45 * double.Parse(text8Hours.Text);
amount10Hours = amount10Hours * double.Parse(text10Hours.Text) -
break45 * double.Parse(text10Hours.Text);
// Adds all together to output final amount of hours
answer = amount4Hours + amount8Hours + amount10Hours;
labSubtotal.Text = answer.ToString();
}
}
private void btnPay_Click(object sender, EventArgs e)
{
// Hourly pay stored here
double hourpay = 6.19;
hourpay = hourpay * double.Parse(labSubtotal.Text);
labPay.Text = hourpay.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
// Resets all text boxes back to blank
text4Hours.Text = string.Empty;
text8Hours.Text = string.Empty;
text10Hours.Text = string.Empty;
labSubtotal.Text = string.Empty;
labPay.Text = string.Empty;
}
}
}
The Problem...
When I type in three different numbers in each text box, I get the outcome just perfect.
If I hit the clear button, it does what I ask and removes everything from the output
If I enter three numbers again (same ones or different ones) after it has been cleared, I will get different output.
I think it has something to do with the clear code because it's not resetting the values to zero like it does at the start of the program. I have tried setting the clear code to input zeros, but that doesn't help; just gives the same problem.

This is a good case to show how to use the debugger. Put a breakpoint on the line:
amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
Then when you calculate the answer, watch how the amount4Hours variable changes.
This type of bug shows why people avoid the use of global variables.

private double amount4Hours = 4;
private double amount8Hours = 8;
private double amount10Hours = 10;
This code should go into your btnSubtotal_Click.

amount4Hours = 4;
amount8Hours = 8;
amount10Hours = 10;
Put this code in clear button. You also need to reset your global variables.

As others have said, on a general point you need to use the debugger for figuring out why something hasn't worked as you expected. In this case you are creating 3 global variables at the beginning (amount4hours etc.) and then manipulating them later on when clicking btnSubmit. At no point when btnClear do you reset your global values. Try adding in your btnClear_Click method:
amount4hours = 4;
amount8hours = 8;
amount10hours = 10;
This will reset your global variables.

If the global variables value should not be updated,why not directly get the value of answer by having their sum value directly
/*amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
*
* amount8Hours = amount8Hours * double.Parse(text8Hours.Text) -
* break45 * double.Parse(text8Hours.Text);
*
* amount10Hours = amount10Hours * double.Parse(text10Hours.Text) -
* break45 * double.Parse(text10Hours.Text);
*
* answer = amount4Hours + amount8Hours + amount10Hours;*/
answer = amount4Hours * double.Parse(text4Hours.Text) +
amount8Hours * double.Parse(text8Hours.Text) -
break45 * double.Parse(text8Hours.Text) +
amount10Hours * double.Parse(text10Hours.Text) -
break45 * double.Parse(text10Hours.Text);
By the way, your error checking is fail because you stored all checking result in same variable therefore only the third textbox content is checked based on your logic. I assume you display the MessageBox whenever one of three textbox have invalid input. Then,
//bool isNumber = true;
//true false statement for error checking
//isNumber = double.TryParse(text4Hours.Text, out outputValue);
//isNumber = double.TryParse(text4Hours.Text, out outputValue);;
//isNumber = double.TryParse(text10Hours.Text, out outputValue);
//if (!isNumber)
if (!double.TryParse(text4Hours.Text, out outputValue)||
!double.TryParse(text8Hours.Text, out outputValue)||
!double.TryParse(text10Hours.Text, out outputValue))
{
//error checking for blank text boxes
//the checking only check if they are double type
//but not checking the range from 0 to 9
MessageBox.Show("Enter a number from 0-9");
}

Related

If an user does not input a local variable how do i define it using other variables? C#

Let me explain.
I am a high school student with not a lot of expirience programming in C#, we have an asigment to make a geometry calculator i got a triangular pyramid, but thats beside the point. The calculator is suposed to get an imput from the user and then with that given data calculate the surface and the volume.
double a = Convert.ToDouble(Console.ReadLine());
double h = Convert.ToDouble(Console.ReadLine());
double H = Convert.ToDouble(Console.ReadLine());
double area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
double volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Now thats easy for me , but a problem arises when the user does not know the value of one of the variables for example the hight.In such a instance the calculator is suposed to calculate it using the other two local variables.
double h = Convert.ToDouble(Console.ReadLine());
double h = Math.Sqrt(Math.Pow(a * Math.Sqrt(3) / 3, 2) + Math.Pow(H));
I know i know you cant do this but i coudn't find anything on the internet, so i beg you for help since this is 20% of my grade.
And if this can't be done do you have any other sugestions.
P.s. Sorry if my english is bad.
This is fairly simple to accomplish. Not having a variable means that you'll have a different formula/calculation depending on the missing variable, you can do this with if conditionals.
//Read them in as strings if you want to check if they're "_blank_", convert them
later.
string a = Console.ReadLine();
string h = Console.ReadLine();
string H = Console.ReadLine();
double area = 0;
double volume = 0;
if(a == "") //If it's blank, no entry do this code.
{
//This is how I'd convert it, just a little less pretty for the sake
//of understanding for you. You'd need to do this in every if block.
double returnedDoubleh = ConvertToDouble(h);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `a` is blank.
}
else if (h == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `h` is blank.
}
else if (H == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleh = ConvertToDouble(h);
//Have your formula if `H` is blank.
}
else //This is if none are blank OR More than one is blank which would crash if
more than one is blank..
{
area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
}
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Example Function to convert your string values.
public static double ConvertToDouble(string nonConverted)
{
double converted;
while (!double.TryParse(nonConverted, out converted) || String.IsNullOrWhiteSpace(nonConverted))
{
Console.Clear();
Console.WriteLine($"INVALID RESPONSE\n\r" +
$"\n\rTry Again");
nonConverted = Console.ReadLine();
}
return converted;
}
In your conditionals you can also use a "Variable" so instead of saying if(a == "") you could do something like if(a == "x")

c# empty textboxs after click

I have this problem where I run my code and it gives me empty text boxs and I'm not sure why. I have debug it and found that number = double.Parse(txtTableAvgTemp.Text); and poolCost = double.Parse(txtTableDollars.Text); are both returning NULL. The code is to work out the heating cost of the pool in question as per size.
const double poolLengthMin = 5; // min pool length
const double poolLengthMax =50; // max pool length
const double poolWidthMin = 2; // min pool width
const double poolWidthMax = 20; // max pool width
const double poolDepthMin = 2; // min pool depth
const double poolDepthMax = 4; // max pool depth
// variable used in btnCalculate_Click
float poolLength;
float poolWidth;
float poolDepth;
float SurfaceArea = 0;
float Volume = 0;
const int poolSize = 0;
const int smallPool = 500000 ;
const int mediumPool = 1500000;
const double poolTemp = 1.5;
double poolDegreesMin = 5;
double poolDegreesMax = 25;
double number;
double costToHeatPool;
double heatingVolume;
double poolDegrees = 5;
/* validation statements for pool
* length, width and depth
*/
bool ValidPoolLength(double poolLength)
{
if (poolLength >= poolLengthMin && poolLength <= poolLengthMax)
{
return true;
}
else
{
return false;
}
}
bool ValidPoolWidth(double poolWidth)
{
if (poolWidth >= poolWidthMin && poolWidth <= poolWidthMax)
{
return true;
}
else
{
return false;
}
}
bool ValidPoolDepth(double poolDepth)
{
if(poolDepth >= poolDepthMin && poolDepth <= poolDepthMax)
{
return true;
}
else
{
return false;
}
}
// end of validation statements
private void lblCategory_Click(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{ // convert variable to float from double from string
poolLength = float.Parse(txtLength.Text);
poolWidth = float.Parse(txtWidth.Text);
poolDepth = float.Parse(txtAvgDepth.Text);
//clear string
txtVolume.Clear();
txtSurfaceArea.Clear();
txtTableDollars.Clear();
// error massages for pool length
//pool width and pool depth
if (!(ValidPoolLength(poolLength)))
{
MessageBox.Show("Length measurement is invalid \r\n Please enter a value between : " + poolLengthMin + " and " + poolLengthMax, "Pool Lenght Invalid" , MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (!(ValidPoolWidth(poolWidth)))
{
MessageBox.Show("Width measurment is invalid \r\n Please enter a value between : " + poolWidthMin + " and " + poolWidthMax, "Pool Width Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (!(ValidPoolDepth(poolDepth)))
{
MessageBox.Show("Pool Depth is invalid \r\n Please enter a value between : " + poolDepthMin + " and " + poolDepthMax, "Pool Depth Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
// caclulate surface area and show in txtSurfaceArea
SurfaceArea = poolLength * poolWidth;
txtSurfaceArea.Text += SurfaceArea;
//calculate pool volume and show in txtVolume
Volume = poolLength * poolWidth * poolDepth * 1000;
txtVolume.Text += Volume;
//calculate size of pool Small, Medium or large
//and show in lblcategory
Volume = float.Parse(txtVolume.Text);
if (poolSize <= smallPool && smallPool >= Volume)
{
lblCategory.Text = "Pool Category: Small";
}
else if (poolSize <= mediumPool && mediumPool >= Volume)
{
lblCategory.Text = "Pool Category: Medium";
}
else
{
lblCategory.Text = "Pool Category: Large";
}
//cost to heat the pool to 25 degrees
while (poolTemp >= poolDegrees && poolTemp < poolDegrees)
{
number = poolDegrees + poolTemp;
txtTableAvgTemp.Text += number.ToString() + "\r\n";
poolDegrees += poolTemp;
//variable for costing out heating of pool
double poolCost = costToHeatPool;
heatingVolume = float.Parse(txtVolume.Text);
costToHeatPool = float.Parse(txtVolume.Text);
poolCost = double.Parse(txtTableDollars.Text);//empty ?
number = double.Parse(txtTableAvgTemp.Text);//empty ?
poolCost = (Math.Truncate(poolCost));
//formula for costing of heating to pool
costToHeatPool = (25 - number) * heatingVolume / 32500;
txtTableDollars.Text += poolCost + "\r\n";
}
}
I have given you my whole code as I'm not sure where I have gone wrong. I did try poolDegreesMin and poolDegreesMax.
I just see some problems with the parsing itselve. You parse the text of txtTableAvgTemp.Text.
This text is extended for each while loop with a new line of temperature:
txtTableAvgTemp.Text += number.ToString() + "\r\n";
This will never parse.
Further on, on the first cycle the text is empty ("", which is not null). This will also throw a FormatException.
Initialize the text box first with a 0. And don't add new lines to a text box if you want to parse from them later. You should use temporary double fields to store the last values. Then there is no need for parsing the whole time.
// init with 0
txtTableDollars.Text = 0;
txtTableAvgTemp.Text = 0;
double currentCost = 0;
// do them outside, no need to do it on every loop
float heatingVolume = float.Parse(txtVolume.Text);
// working while
while (poolDegrees >= 3.5 && poolDegrees < 23)
{
poolDegrees += poolTemp;
double costToHeatPool = (25 - poolDegrees) * heatingVolume / 32500;
currentCost += costToHeatPool;
txtTableAvgTemp.Text += poolDegrees + System.Environment.NewLine;
txtTableDollars.Text += currentCost + System.Environment.NewLine;
}
Additional point: I do not know exactly, but this while loop here looks realy suspicious
while (poolTemp >= poolDegrees && poolTemp < poolDegrees) {/*...*/}
For me this looks like a while(false). Is this intended? this loop should never be executed...
Well, in the beginning of your code there is line of code:
txtTableDollars.Clear();
is clears textbox, so later when you're using that text, obviously it is empty:
poolCost = double.Parse(txtTableDollars.Text);
And later in the same loop - you're assigning it like
txtTableDollars.Text += poolCost + "\r\n";
so if your loop will be executed more than once - you will get some strange result (or exception) when parsing it again.
It looks like you should divide your computation from visualisation. Parse your input once and use numbers for computation, don't reparse text values again.

c# Percentage calculator

I have little problem, and I need help..
So here is my problem I have created win form in c# and used numericupdown element to insert my numbers, but I cant calculate percent. Here is the code below:
private void button8_Click(object sender, EventArgs e)
{
int x, y, sum;
x = Convert.ToInt16(numericUpDown7.Value);
y = Convert.ToInt16(numericUpDown8.Value);
sum = x * 3.4528 + 21%;
textBox5.Text = Convert.ToString(sum);
}
What I need to do is to insert x and press button to calculate this formula
example: x * 3.4528 + 21 % = ???
Maby someone has options to help me.
Thanks for all of you, who will help me!
Try this
sum = (x * 3.4528) * 1.21;
private void button1_Click(object sender, EventArgs e)
{
double eng, urdu, math, cs, tot, per;
eng = Convert.ToDouble(txtenglish.Text);
urdu = Convert.ToDouble(txturdu.Text);
math = Convert.ToDouble(txtmath.Text);
cs = Convert.ToDouble(txtcs.Text);
tot = eng + urdu + math + cs;
lbltotal.Text = Convert.ToString(tot);
per = (tot / 400) * 100;
lblpercent.Text = Convert.ToString(per);
}
First off you need to use decimal, float, or double instead of int (you can find many references online about each to help you determine which would be best for you). Otherwise it will just truncate the answer and drop anything after the decimal point. Second you need to use the formula that everyone else has mentioned sum = x * 3.4528 * 1.21.

Input String was not in a correct form

There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();
You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.
If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0
First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.
the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....
Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.

how to use the round maths function in asp.net?

I am use the textbox value like 1455.23, use the round function my output is 0000145523 but customer not enter float values like 1234 my output is 0000123400 pls give me suggestion
my code is format.cs
public bool formatAmount(float flAmount, out string strOutput)
{
bool bval = false;
float rounded = (float)Math.Round(flAmount, 2);
if(rounded!=null)
{
flAmount = flAmount * 100;
strOutput = Convert.ToString(flAmount);
bVal = true;
}
return bVal;
}
In my asp page code like this
string ods;
float a = Convert.Todecimal(txtSSA.Text);
string sss = oclsUtility.formatAmount(a, out ods);
I am assuming you want to ignore the multiplication of 100 part in case the fractional value is not there.
So 1234 in your case is essentially 1234.00 and you need to avoid the 0000123400
float flAmount = 15F;
float rounded = (float)Math.Round(flAmount, 2);
double fractionalval = (rounded - Math.Floor(rounded)) * 100;
if(fractionalval > 0)
flAmount = flAmount * 100;
After this i presume rest might work and pad it to 10 length string.
This would skip the multiplication if there are fractional parts, hope this is what you need else please edit for additional information.
If I'm understanding you, you need to keep leading 0 if user input is float and if not removes them. You can try this:
int number;
bool result = Int32.TryParse(rounded, out number);
if (result)
{
// Your number will contain the number with no leading 0
}
else
{
// Then you have a float.
}

Categories

Resources