Simple console output formatting - c#

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);

Related

How do I add the last typed number to a total?

I'm new to learning C# and I was wondering how to keep adding numbers I type to a total number. Right now instead of adding up all the numbers I typed in before typing 0, it just takes the last typed in number... The number count does go up however, which is why I'm pretty confused.
For example:
Enter number: 2
Enter number: 6
Enter number: 4
Enter number: 7
Enter number: 0
There are 4 positive numbers (Works like I intended)
The total amount is 7 (Is supposed to be 2+6+4+7 = 21)
Console.Write("Enter number: ");
string numberInput = Console.ReadLine();
double number = double.Parse(numberInput);
int count = 0;
double begin = 0;
double total = 0;
while (number != 0)
{
if (number >= 0)
{
count++;
total = begin + number;
}
Console.Write("Enter number: ");
number = double.Parse(Console.ReadLine());
}
double average = total / count;
Console.WriteLine("There are {0} positive numbers", count);
Console.WriteLine("The total amount is {0}", total);
Console.WriteLine("Your average is: {0}", average);
Console.ReadKey();
I figured it out already, had to change this:
total = begin + number;
to
total = total + number;
You don't need to use begin variable as you can sum input values like below:
total += number; // This is the same with 'total = total + number;'
As a suggestion, you can improve your code using do while loop like below:
int count = 0;
double total = 0;
double number;
do
{
Console.Write("Enter number: ");
number = double.Parse(Console.ReadLine());
if (number > 0)
{
count++;
total += number;
}
} while (number != 0);
double average = total / count;
Console.WriteLine("There are {0} positive numbers", count);
Console.WriteLine("The total amount is {0}", total);
Console.WriteLine("Your average is: {0}", average);
Console.ReadKey();

C# "Method Name Expected"

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);

How do I get this WHILE loop to work?

Currently doing an exercise that I thought I had done right, using an IF ELSE statement, but once submitted I was told instead to use a WHILE or DO-WHILE loop, and I'm having a bit of trouble. You'll see where I've used the WHILE loop, but it is giving me an infinite loop of the error message that I assigned to it and I don't know how to make it stop!
static void Main(string[] args)
{
decimal hours;
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
decimal parkingCost = hours * HOURLY_RATE;
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
}
if (parkingCost > MAX_FEE)
{
Console.Write("Total fee is $" + MAX_FEE);
Console.WriteLine(" Time parked in hours is " + hours);
}
else
{
parkingCost = hours * HOURLY_RATE;
Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
Console.WriteLine("Time parked in hours is " + hours);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
So the idea is that I want for the "Enter correct amount of hours - 1 to 24. " to display if the user enters a number less than 1 or greater than 24, otherwise for the program to go ahead with the IF and ELSE statements.
Just add the line accepting input inside the while loop as shown below
static void Main(string[] args)
{
decimal hours;
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
decimal parkingCost = hours * HOURLY_RATE;
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
hours = decimal.Parse(Console.ReadLine());
}
parkingCost = hours * HOURLY_RATE; // to recalculate
if (parkingCost > MAX_FEE)
{
Console.Write("Total fee is $" + MAX_FEE);
Console.WriteLine(" Time parked in hours is " + hours);
}
else
{
parkingCost = hours * HOURLY_RATE;
Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
Console.WriteLine("Time parked in hours is " + hours);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
You forgot to read the value in the while loop again to get a new value:
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
}
Or as a Do While you can get rid of the first read and only loop on error
do {
Console.WriteLine("Enter the amount of hours parked:");
try{
hours = decimal.Parse(Console.ReadLine());
if(hours <1 || hours > 24)
Console.Write("Enter correct amount of hours - 1 to 24. ");
}
catch { Console.WriteLine("Please enter a valid numeric value"); }
} while(hours < 1 || hours > 24);
I added the try catch because if they enter a value that is not numeric it can throw an error.

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