C# "Method Name Expected" - c#

I'm making a very simple BMI Calculator that I had working already but had to change a rounding problem, now I'm running into "Method name expected" for the final output of userWeight and userHeight. Here is the code.
double userWeight;
double userHeight;
double userAnswer;
Console.WriteLine("Welcome to our program for calculating Body Mass Index");
Console.WriteLine("Please enter your weight in pounds.");
userWeight = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter your height in inches.");
userHeight = double.Parse(Console.ReadLine());
userAnswer = (userWeight / (userHeight * userHeight) * 703);
Console.WriteLine("The BMI of a person who weighs ") + userWeight ("pounds and is ") + userHeight ("inches tall has a BMI of ") + userAnswer;
Console.WriteLine("Press any key to exit...");
Console.ReadKey();

The format of your Console.WriteLine is a bit off. You wrote:
Console.WriteLine("The BMI of a person who weighs ") + userWeight ("pounds and is ") + userHeight ("inches tall has a BMI of ") + userAnswer;
But what you want to do is this:
Console.WriteLine("The BMI of a person who weighs " + userWeight + " pounds and is " + userHeight + " inches tall has a BMI of " + userAnswer);
There are other ways to format a string as the other folks have mentioned but this is adequate as well :).

The problem is with your Writeline() method. Please change it this way:
Console.WriteLine($"The BMI of a person who weighs {userWeight} pounds and is {userHeight} inches tall has a BMI of {userAnswer}");

You can try this one: This prints double with two decimal digits.
Console.WriteLine(string.Format("The BMI of a person who weighs {0:0.00} pounds and is {1:0.00} inches tall has a BMI of {2:0.00}", userWeight, userHeight, userAnswer));
else simple way is:
Console.WriteLine("The BMI of a person who weighs " + userWeight + " pounds and is " + userHeight + " inches tall has a BMI of " + userAnswer);

Related

Read() only takes first input but no other input from other Console.Read()

I am following instructions in a C# Tutorial video that is great. I am building a file with the notes and code from the video.
I reviewed similar questions but they do not solve this problem.
Here is a copy of the CS file:
static void Main(string[] args)
{
// Single line comments
/* test multi-line comments
* asldkjasldkjaskd
* asldkjasldkja
* alsdkjalksdj
* */
Console.WriteLine("Hello world!");
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
bool canVote = true;
char grade = 'A';
// Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
//Long with max value of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
// Decimal has a max value of 79,228,162,514,264,337,593,543,950,335
// If you need something bigger, look up BigInteger
decimal maxDecimal = decimal.MaxValue;
// A float is a 32 bit number with a max value of 3.402823E+38 with 7 decimal positions
float maxFloat = float.MaxValue;
// A double is a 32 bit number with a max value of 1.797693134E+308 with 15 decimal positions
double maxDouble = double.MaxValue;
Console.WriteLine("Max Int : " + maxInt);
Console.WriteLine("Max Long : " + maxLong);
Console.WriteLine("Max Decimal : " + maxDecimal);
Console.WriteLine("Max Float : " + maxFloat);
Console.WriteLine("Max Double : " + maxDouble);
var anotherName = "Tom";
// anotherName = 2; Cannot implicitly convert a gype 'int' to a 'string'
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());
// Math
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));
Console.WriteLine("++i = " + (++i));
Console.WriteLine("i-- = " + (i--));
Console.WriteLine("--i = " + (--i));
Console.WriteLine("i +- 3 = " + (i +- 3));
Console.WriteLine("i -= 2 = " + (i -= 2));
Console.WriteLine("i *= 2 = " + (i *= 2));
Console.WriteLine("i /= 2 = " + (i /= 2));
Console.WriteLine("i %= 2 = " + (i %= 2));
// casting
// if no magnitude is lost, casting will happen automatically. But otherwise, you set it up as follows
double pi = 3.14;
int intPi = (int)pi;
Console.WriteLine("intPi = " + intPi);
// Math functions
// Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("number1 is " + number1);
Console.WriteLine("number2 is " + number2);
Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
Console.WriteLine("Math.Ceiling(number2) " + (Math.Ceiling(number1)));
Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
Console.WriteLine("Math.Max(number1,number2) " + (Math.Max(number1,number2)));
Console.WriteLine("Math.Min(number1,number2) " + (Math.Min(number1,number2)));
Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));
// random numbers
Random rand = new Random();
Console.WriteLine("Random number between 1 and 10 is " + rand.Next(1, 11));
// Relational operators : > < >= <= == !=
// Logical operators : && || ^ !
// note: ^ is the exclusive or
Console.WriteLine("What is your child's age? (enter 0 - 18)");
int age = Console.Read();
if ((age >= 5) && (age <= 7))
{
Console.WriteLine("Go to Elementary School");
} else if ((age > 7) && (age <= 13))
{
Console.WriteLine("Go to middle school");
} else if ((age < 5) || (age > 13))
{
Console.WriteLine("Your child does not meet our age requirements.");
} else
{
Console.WriteLine("Go to high school");
}
Console.WriteLine("What is your age? ");
int workingAge = Console.Read();
if ((workingAge < 14) || (workingAge > 67))
{
Console.WriteLine("You shouldn't work.");
}
}
The program ignores the input from the following:
Console.WriteLine("What is your age? ");
int workingAge = Console.Read();
The output is:
What is your age?
You shouldn't work.
So, the program is not stopping for my input, but rather seems to process its conditions based on the previous integer input value of 2 or 5.
Other articles talked about doing the following which I tried with no avail:
Console.WriteLine("What is your age? ");
int workingAge = Convert.ToInt32(Console.Read());
And
Console.WriteLine("What is your age? ");
int workingAge = int32.Parse(Console.Read());
The second one produced an error in Visual Studio The name 'int32' does not exist in the current context
I updated the script to use int.Parse(Console.ReadLine()), and it worked on Visual Studio 2007, but I ran this on Visual Studio 2015 Community Edition and it is doing the same exact thing as if the changes had no effect:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Single line comments
/* test multi-line comments
* asldkjasldkjaskd
* asldkjasldkja
* alsdkjalksdj
* */
Console.WriteLine("Hello world!");
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
bool canVote = true;
char grade = 'A';
// Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
//Long with max value of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
// Decimal has a max value of 79,228,162,514,264,337,593,543,950,335
// If you need something bigger, look up BigInteger
decimal maxDecimal = decimal.MaxValue;
// A float is a 32 bit number with a max value of 3.402823E+38 with 7 decimal positions
float maxFloat = float.MaxValue;
// A double is a 32 bit number with a max value of 1.797693134E+308 with 15 decimal positions
double maxDouble = double.MaxValue;
Console.WriteLine("Max Int : " + maxInt);
Console.WriteLine("Max Long : " + maxLong);
Console.WriteLine("Max Decimal : " + maxDecimal);
Console.WriteLine("Max Float : " + maxFloat);
Console.WriteLine("Max Double : " + maxDouble);
var anotherName = "Tom";
// anotherName = 2; Cannot implicitly convert a gype 'int' to a 'string'
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());
// Math
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));
Console.WriteLine("++i = " + (++i));
Console.WriteLine("i-- = " + (i--));
Console.WriteLine("--i = " + (--i));
Console.WriteLine("i +- 3 = " + (i + -3));
Console.WriteLine("i -= 2 = " + (i -= 2));
Console.WriteLine("i *= 2 = " + (i *= 2));
Console.WriteLine("i /= 2 = " + (i /= 2));
Console.WriteLine("i %= 2 = " + (i %= 2));
// casting
// if no magnitude is lost, casting will happen automatically. But otherwise, you set it up as follows
double pi = 3.14;
int intPi = (int)pi;
Console.WriteLine("intPi = " + intPi);
// Math functions
// Acos, Asin, Atan, Atan2, Cos, Cosh, Exp, Log, Sin, Sinh, Tan, Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("number1 is " + number1);
Console.WriteLine("number2 is " + number2);
Console.WriteLine("Math.Abs(number1) " + (Math.Abs(number1)));
Console.WriteLine("Math.Ceiling(number2) " + (Math.Ceiling(number1)));
Console.WriteLine("Math.Floor(number1) " + (Math.Floor(number1)));
Console.WriteLine("Math.Max(number1,number2) " + (Math.Max(number1, number2)));
Console.WriteLine("Math.Min(number1,number2) " + (Math.Min(number1, number2)));
Console.WriteLine("Math.Pow(number1, 2) " + (Math.Pow(number1, 2)));
Console.WriteLine("Math.Round(number1) " + (Math.Round(number1)));
Console.WriteLine("Math.Sqrt(number1) " + (Math.Sqrt(number1)));
// random numbers
Random rand = new Random();
Console.WriteLine("Random number between 1 and 10 is " + rand.Next(1, 11));
// Relational operators : > < >= <= == !=
// Logical operators : && || ^ !
// note: ^ is the exclusive or
Console.WriteLine("What is your child's age? (enter 0 - 18)");
int age = int.Parse(Console.ReadLine());
if ((age >= 5) && (age <= 7))
{
Console.WriteLine("Go to Elementary School");
}
else if ((age > 7) && (age <= 13))
{
Console.WriteLine("Go to middle school");
}
else if ((age < 4) || (age > 18))
{
Console.WriteLine("Your child does not meet our age requirements.");
}
else
{
Console.WriteLine("Go to high school");
}
Console.WriteLine("What is your age? ");
int workingAge = int.Parse(Console.ReadLine());
if ((workingAge < 14) || (workingAge > 67))
{
Console.WriteLine("You shouldn't work.");
}
else
{
Console.WriteLine("Work harder and smarter to get ahead.");
}
}
}
}
Please help.
.Read() reads only a single character. You probably want .ReadLine() instead, which reads all the characters up to Enter, and returns a string.
int workingAge = int.Parse(Console.ReadLine());
Expanding off of #recursive you can use int32.TryParse() to check if a valid number was supplied.
bool valid = false;
int workingAge;
while (!valid)
{
valid = int32.TryParse(Console.ReadLine(), out workingAge);
if (!valid)
Console.WriteLine("Supplied number was invalid");
}
// Rest of code
Edit: I think this can be simplified even further by doing the following:
int workingAge;
while (!int32.TryParse(Console.ReadLine(), out workingAge))
{
Console.WriteLine("Supplied number was invalid");
}
// Rest of code
I will add to recursive's solution and explain what is happening.
since you are using Console.Read() in two different areas -
and since Console.Read() reads one key input (i.e '1') -
you are probably entering two different digits in the first occurance which causes the first .Read() to only read the first digit, and "passes" the second digit to the second .Read()
as was said before me, changing the .Read() to .ReadLine() will solve your issue.

Simple console output formatting

There is my program.
static void Main(string[] args)
{
double weeklySales = 0, grossPay = 0, fedTax = 0, socSecurity = 0, retirement = 0, totDeductions = 0, takeHomePay = 0;
Console.WriteLine("Please enter your total for sales for the week.");
weeklySales = Convert.ToDouble(Console.ReadLine());
grossPay = weeklySales * .07;
fedTax = grossPay * .18;
socSecurity = grossPay * .06;
retirement = grossPay * .1;
totDeductions = fedTax + socSecurity + retirement;
takeHomePay = grossPay - totDeductions;
Console.WriteLine("Your total sales for the week were $ ", weeklySales);
Console.WriteLine("Your gross pay for the week was $ ", grossPay);
Console.WriteLine("Your Federal Taxes for the week were $ ", fedTax);
Console.WriteLine("You were deducted $ ", socSecurity, " for social security.");
Console.WriteLine("Your retirement contribution was $ ", retirement);
Console.WriteLine("The total amount of of deductions were $ ", totDeductions);
Console.WriteLine("Your take home pay for the week is $ ", takeHomePay);
Console.ReadLine();
}
The problem is an incorrect output.
Please enter your total for sales for the week.
123
Your total sales for the week were $
Your gross pay for the week was $
Your Federal Taxes for the week were $
You were deducted $
Your retirement contribution was $
The total amount of of deductions were $
Your take home pay for the week is $
I need to include calculated values to output.
How can I do this?
Also, this line won't work:
Console.WriteLine("You were deducted ${0}", socSecurity, " for social security.");
It will need to be:
Console.WriteLine("You were deducted ${0} for social security.", socSecurity);
The other alternative is to use string concatenation:
Console.WriteLine("You were deducted $" + socSecurity + " for social security.");
If I understood your problem correctly, you would just have to replace $ with {0} to show the actual values.
In the current code, you're not specifying where the values should be entered into the string outputs. You can change them as follows and receive the output that you're looking for:
Console.WriteLine("Your total sales for the week were ${0}", weeklySales);
Console.WriteLine("Your gross pay for the week was ${0}", grossPay);
Console.WriteLine("Your Federal Taxes for the week were ${0}", fedTax);
Console.WriteLine("You were deducted ${0} for social security.", socSecurity);
Console.WriteLine("Your retirement contribution was ${0}", retirement);
Console.WriteLine("The total amount of of deductions were ${0}", totDeductions);
Console.WriteLine("Your take home pay for the week is ${0}", takeHomePay);

Math.Round - Does not round answer

I would like to make a program that calculates circumference. Though, would much rather have a rounded answer (two decimal places) as a pose to seven decimal places. But when I use the Math.Round method, it doesn't seem to round. What am I doing wrong?
Console.Write("Circumference Calculator! Enter the radius of the circle: ");
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + ans + " squared.");
Math.Round does not modify provided argument - it returns a new value. So you have to assigned it back to a variable to make it work:
ans = Math.Round(ans, 2);
You have to use the return value of Math.Round, it doesn't take the variable by reference.
//Greet user & give instructions
#region
Console.WriteLine("Circumference Calculator");
Console.WriteLine("");
Console.Write("Welcome to the Circumference Calculator! Please enter the radius of the circle: ");
#endregion
//Get input from user and calculate answer
#region
Console.ForegroundColor = oldColour;
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Console.ForegroundColor = ConsoleColor.DarkYellow;
double roundedAnswer = Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + roundedAnswer + " squared.");
#endregion

Reading and processing input [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Write a program that calculates and displays the take-home pay for a commissioned sales employee after deductions are taken. The employee receives 7% of his or her total sales as his or her gross pay. His or her federal tax rate is 18%. He or she contributes 10% to his or her retirement program and 6% to Social Security. Use the Processing Logic provided in Step 2 below as a guide. The program's output should look something like this:
Enter weekly sales: 28,000
Total sales: $28,000.00
Gross pay (7%): $1,960.00
Federal tax paid: $352.80
Social security paid: $117.60
Retirement contribution: $196.00
Total deductions: $666.40
Take home pay: $1,293.60
Press any key to continue.
//Here is my Code, I am having trouble getting input
//Declarations
int weeklySales;
double grossPay = weeklySales * .07;
double fedTax = grossPay * .18;
double retirement = grossPay * .1;
double socSecurity = grossPay * .06;
double totDeductions = socSecurity + retirement + fedTax;
double takeHomePay = grossPay - totDeductions;
//Promt user for Input
System.Console.WriteLine("What is your weekly Sales?");
weeklySales = Console.Read();
System.Console.ReadLine();
//Output Display
System.Console.Write("\nYour Weekly Sale amount is :\t\t" + weeklySales+ "\n\nGross Pay:\t\t\t\t" + grossPay+ "\n\nFed Tax \t\t\t\t" + fedTax + "\n\nRetirement\t\t\t\t"+ retirement + "\n\nSocial Security:\t\t\t" + socSecurity + "\n\nTotal Deductions:\t\t\t" + totDeductions + "\n\nMaking your take home pay:\t\t" + takeHomePay);
System.Console.ReadLine();
weeklySales = Console.Read();
Is not going to do what you think it does. It will return the ASCII value of the first char.
Instead:
string weeklySalesText = Console.ReadLine();
weeklySales = int.Parse(weeklySalesText ); // may need more processing.
Proper method:
Int32 weeklySales = 0;
while (weeklySales.Equals(0))
{
Console.WriteLine("What are your weekly sales?");
String input = Console.ReadLine();
try
{
weeklySales = Int32.Parse(input);
}
catch
{
Console.WriteLine("There is an error in your input, try again!");
}
}
Double grossPay = weeklySales * .07;
Double fedTax = grossPay * .18;
Double retirement = grossPay * .1;
Double socSecurity = grossPay * .06;
Double totDeductions = socSecurity + retirement + fedTax;
Double takeHomePay = grossPay - totDeductions;
Console.Write("\nYour Weekly Sale amount is :" + weeklySales + "$\nGross Pay: " + grossPay + "$\nFed Tax: " + fedTax + "$\nRetirement: " + retirement + "$\nSocial Security: " + socSecurity + "$\nTotal Deductions: " + totDeductions + "$\nMaking your take home pay: " + takeHomePay + "$");
Console.Read();
Easy method:
Console.WriteLine("What are your weekly sales?");
try
{
Int32 weeklySales = Int32.Parse(Console.ReadLine());
Double grossPay = weeklySales * .07;
Double fedTax = grossPay * .18;
Double retirement = grossPay * .1;
Double socSecurity = grossPay * .06;
Double totDeductions = socSecurity + retirement + fedTax;
Double takeHomePay = grossPay - totDeductions;
Console.Write("\nYour Weekly Sale amount is :" + weeklySales + "$\nGross Pay: " + grossPay + "$\nFed Tax: " + fedTax + "$\nRetirement: " + retirement + "$\nSocial Security: " + socSecurity + "$\nTotal Deductions: " + totDeductions + "$\nMaking your take home pay: " + takeHomePay + "$");
Console.Read();
}
catch
{
Console.WriteLine("There is an error in input. Program will be terminated.");
}
You are trying to calculate the result using the variable before you put anything in the variable, that doesn't work. Do the input before you calculate the result.
Console.Read() doesn't do what you think it does. It gets the first new character, and returns it as an int. It doesn't read the whole line. Also, the Console.ReadLine() call after that is completely meaningless, since you're not doing anything with the result.
I think you want the user to write a line, and then capture the contents of that line, check if it's and int, if it's not write an error message and try again, and if it is, do stuff with it.
This is done as such:
while (!int.TryParse(Console.ReadLine(), out weeklySales))
{
Console.WriteLine("Input was not a number.");
}
Replace
weeklySales = Console.Read();
System.Console.ReadLine();
With that, and afterwards, you can use weeklySales to calculate all other required variables.
Also, the definitions at the start shouldn't work either, as weeklySales isn't initialized at the start.
EDIT: As a little explanation how my method works: you are calling int.TryParse(string, out int), which returns false if it the given string is not a number, and else parses it to an int and returns true.
The thing you want to parse to an integer is the console input, therefore, the first parameter should be Console.ReadLine(). weeklySales is obviously the number you want to convert the string to, and is therefore provided as an out parameter (look that up if you don't know what that is).
If int.TryParse returns false (and has therefore failed), we run the while loop to inform the user, and ask again. If not, then we continue the program.

c# using operators with calculations (net pay) (gross pay)

I don't understand if the calculation for netPay = grossPay - (fedtax withholding + social security tax withholding). Are my calculations correct within the program? Dealing with such in editedTax?? If someone could help I'd appreciate it.
More info: When I display netPay within an output, I receive a runtime error, where I couldn't convert the negative to currency with {0:c2}.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
string empName;
string userInput;
double netPay;
double editedTax1;
double grossPay;
double editedTax2;
double hrsWorked;
double ovtWorked;
double payRate;
const double FED_TAX = .28;
const double SS_TAX = 7.65;
// step 1
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
// step 2
Console.WriteLine(" --------------------------");
// step 3
Console.Write("\n Please enter the employer's name: ");
empName = Console.ReadLine();
//step 4
Console.Write("\n Please enter the number of hours worked this week: ");
userInput = Console.ReadLine();
hrsWorked = Convert.ToDouble(userInput);
// step 5
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
userInput = Console.ReadLine();
ovtWorked = Convert.ToInt32(userInput);
// step 6
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
userInput = Console.ReadLine();
payRate = Convert.ToDouble(userInput);
// step 7
grossPay = (hrsWorked * payRate + ovtWorked * 1.5 * payRate);
// step 8
editedTax1 = FED_TAX * grossPay;
// step 9
editedTax2 = SS_TAX * grossPay;
// step 10
netPay = editedTax1 + editedTax2 - grossPay;
// step 11
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
// step 12
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", editedTax1);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", editedTax2);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
}
}
}
netPay is assigned the opposite value in the code as compared to your description below.
I don't see any syntax errors or anything.
What is the problem you're having? What are some of the things you've tried?
The reason you're getting a negative number in the calculation is because your SS_TAX is 7.65. I think the number you want is 0.0765.
I'm not sure exactly what you're asking for, but simple substitution in the assignment statements yields the following formulas:
Since
editedTax1 = FED_TAX * grossPay;
editedTax2 = SS_TAX * grossPay;
netPay = editedTax1 + editedTax2 - grossPay;
then
netPay = FED_TAX * grossPay + SS_TAX * grossPay - grossPay;
meaning
netPay = grossPay * (FED_TAX + SS_TAX - 1);
so something seems a little off here...
Are you sure you don't want
netPay = grossPay - (editedTax1 + editedTax2);
instead of
netPay = editedTax1 + editedTax2 - grossPay;
This seems to match what you're looking for as
netPay = grossPay - (FED_TAX * grossPay + SS_TAX * grossPay);
or
netPay = grossPay * (1 - (FED_TAX + SS_TAX));
...unless I'm missing something, of course.
Edit: I was missing something. Your tax constants are a percent, but you're not dividing by 100 when you do calculations with them. You have two options:
Divide by 100 when you use the values in a calculation, like:
editedTax1 = (FED_TAX / 100) * grossPay;
Store the constants as the decimal representation, not a percent, like:
const double FED_TAX = .0028;
I have tested this code on my machine and it works correctly:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
const double FEDERAL_TAX_RATE= 0.28;
const double SOCIAL_SECURITY_RATE = 0.0765; // I am assuming the 7.65 was supposed to be 7.65%... therefore it should be 0.0765
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
Console.WriteLine(" --------------------------");
Console.Write("\n Please enter the employer's name: ");
string empName = Console.ReadLine();
Console.Write("\n Please enter the number of hours worked this week: ");
double hrsWorked = Convert.ToDouble(Console.ReadLine());
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
double ovtWorked = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
double payRate = Convert.ToDouble(Console.ReadLine());
double grossPay = CalculateGrossPay(hrsWorked, payRate, ovtWorked);
double federalTaxWithheld = CalculateTax(grossPay, FEDERAL_TAX_RATE);
double socialSecurityWithheld = CalculateTax(grossPay, SOCIAL_SECURITY_RATE);
double netPay = CalculateNetPay(grossPay, federalTaxWithheld + socialSecurityWithheld);
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", federalTaxWithheld);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", socialSecurityWithheld);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
Console.ReadLine(); // You don't need this line if your running from the command line to begin with
}
static double CalculateGrossPay(double HoursWorked, double PayRate, double OvertimeHoursWorked)
{
return PayRate * (HoursWorked + 1.5 * OvertimeHoursWorked);
}
static double CalculateTax(double GrossPay, double TaxRate)
{
return GrossPay * TaxRate;
}
static double CalculateNetPay(double GrossPay, double TaxAmount)
{
return GrossPay - TaxAmount;
}
}
}
Since it looks as though this is your first programming course, I'll offer you some pointers that they probably will not emphasize in your class:
Use descriptive variable names. If you notice yourself putting a number after your variable name, it can probably done a different and more readable way!
Utilize functions, they bundle common tasks in one section of code and increase readability significantly.
You may want to add some exception handling or validation to this code. For example, what if you accidentally passed -1 into OverTimeHours?
I understand this might not matter at this point in your programming journey, but it's always good to start off using coding techniques that make your code more readable and less confusing, especially for people who may have to maintain it in the future.

Categories