So I'm trying to make a console application that calculates interest rates per year. But somehow its crashing down when i assign the deposit year.
The source code is below:
using System;
namespace week0502
{
class Interest
{
static void Main(string[] args)
{
decimal p = 0; // principle
decimal r = 1; // interest rate
decimal t = 2; // time/years entered
decimal i = 3; // interest
decimal a = 4; // new amount
// prompt for values
Console.Write("Enter original deposit amount: ");
p = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter annual interest rate (10% as 10): ");
r = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter years to save this deposit amount: ");
t = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine();
// display headers
Console.WriteLine("Year Rate Amount Interest New Amount");
// calculate new amount on deposit after t amount of years
for (int n = 1; n <= t; n++)
{
// calculations
i = p * r;
a = i + p;
// display contents
Console.WriteLine("{0, 4}{1, 4}{2, 10:C}{3, 5}{4, 10:C}", n, r, p, i, a);
} // end for
} // end main
} // end class
} // end name
If you mean it closes after showing the result thats normal if you forget to add Console.ReadLine() (wait for user to press enter before closing the application)
using System;
namespace week0502
{
class Interest
{
static void Main(string[] args)
{
decimal p = 0; // principle
decimal r = 1; // interest rate
decimal t = 2; // time/years entered
decimal i = 3; // interest
decimal a = 4; // new amount
// prompt for values
Console.Write("Enter original deposit amount: ");
p = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter annual interest rate (10% as 10): ");
r = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter years to save this deposit amount: ");
t = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine();
// display headers
Console.WriteLine("Year Rate Amount Interest New Amount");
// calculate new amount on deposit after t amount of years
for (int n = 1; n <= t; n++)
{
// calculations
i = p * r;
a = i + p;
// display contents
Console.WriteLine("{0, 4}{1, 4}{2, 10:C}{3, 5}{4, 10:C}", n, r, p, i, a);
} // end for
Console.ReadLine(); //Add this to prevent application from closing
} // end main
} // end class
}
Related
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 2 years ago.
Improve this question
This is for an assignment, please see question and the code i wrote below.
The question:
In the U.S coin system, the penny is the basic coin, and it is equal to cent, a nickel is equivalent to 5 cents, a dime is equivalent to 10 cents, a quarter is equivalent to 25 cents, and half-dollar is equivalent to 50 cents. Design and implement a program that would make use of the functions shown below. Each function has a single int formal parameter Amount.
a) HalfDollars (): Compute the maximum number of half-dollars that could be used in making change for Amount.
b) Quarters():Compute the maximum number of quarter that could be used in making change for Amount
c) Dimes ():Compute the maximum number of dimes that could be used in making change for Amount
d) Nickels () : Compute the maximum number of nickels that could be used in making change for Amount
The code that i wrote:
//Question 1
//please note, i dont have comments everywhere
{
public class MoneyCalc
{
public int Amount;
//a)
public void Half_Dollar()
{
int hd = 2;
int hdOutput = Amount * hd;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + hdOutput);
}
//b)
public void Quater()
{
int q = 4;
int qOutput = Amount * q;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + qOutput);
}
//c)
public void Dimes()
{
int d = 10;
int dOutput = Amount * d;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + dOutput);
}
//d)
public void Nickles()
{
int n = 20;
int nOutput = Amount * n;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + nOutput);
}
}
class Program
{
static void Main(string[] args)
{
//the main program.
//everything is initialised here.
//gets the amount the ser wants to calculate through user input in a string and converts to to an integer.
Console.WriteLine("Please enter an amount to calculate:");
string userAmount = Console.ReadLine();
int amount = Int32.Parse(userAmount);
//users have to make a selection from this list.
Console.WriteLine("");
Console.WriteLine("Please choose what you want to calculate you amount to (Select the number):");
Console.WriteLine("1. Half Dollar");
Console.WriteLine("2. Quater");
Console.WriteLine("3. Dime");
Console.WriteLine("4. Nickel");
//gets the users input(their choice) in a string and coverts it to an integer
string userChoice = Console.ReadLine();
int choice = Int32.Parse(userAmount);
if (choice == 1)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Half_Dollar();
}
else if (choice == 2)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Quater();
}
else if (choice == 3)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Dimes();
}
else if (choice == 4)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Nickles();
}
else
{
Console.WriteLine("Invalid Option");
}
}
}
}
I think, what they looking for is
// amount expected in $$, $2.34
public int GetNumberOfCoins(decimal amount, CoinOption centValue)
{
// you might want to check first if result of truncate is larger than max int value
int numberOfCoins = Convert.ToInt32(Math.Truncate(amount * 100 / (int)centValue));
return numberOfCoins;
}
// And then in your console
public enum CoinOption : int
{
Penny = 1,
Nickel = 5,
Dime = 10,
Quarter = 25,
Half = 50
}
string answer = null;
CoinOption opt;
switch (inputOption)
{
case "1":
opt = CoinOption.Penny;
break;
case "2":
opt = CoinOption.Nickel;
break;
case "3":
opt = CoinOption.Dime;
break;
case "4":
opt = CoinOption.Quarter;
break;
case "5":
opt = CoinOption.Half;
break;
}
// inputAmount originally comes as string but needs to be converted to decimal
answer = GetNumberOfCoins(inputAmount, opt).ToString()
I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}
Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}
In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);
Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}
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>();
I wrote some code to take in five Social Security Numbers, five gross income entries, and calculate tax for each one. The program will use default values for dollar limit, low rate, and high rate to calculate tax owed. But it will also let user to choose if he/she wants to use their own dollar limit, low rate, and high rate to calculate tax owed for a chosen taxpayer.
Problem:
Whenever I enter my own dollar limit, low rate, and high rate to calculate tax owed it still uses default values (limit = 30000, low rate = .15 and high rate = .28). And that's how a get the wrong calculated tax owed values.
Question.
Could it be because my "public static void GetRates(int income)" doesn't have a return type (it is void)? Should I be returning a value back to main after I call "Taxpayer.GetRates(taxPayer[x].grossIncome);" method?
Part of the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace assignment
{
public class Rates
{
public int incomeLimit; // income limit
public double lowTaxRate; // low tax rate
public double highTaxRate; // high tax rate
public int IncomeLimit // read only property
{
get
{
return incomeLimit;
}
}
public double LowTaxRate // read only property
{
get
{
return lowTaxRate;
}
}
public double HighTaxRate // read only property
{
get
{
return highTaxRate;
}
}
public Rates()
{
DoRates();
}
public void DoRates() // class constructor that assigns default values
{
// set default values for limit, lowRate, and highRate
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
public void DoRates(int limit, double lowRate, double highRate) // class constructor that takes three parameters
{
incomeLimit = limit;
lowTaxRate = lowRate;
highTaxRate = highRate;
}
// CalculateTax method that takes an income parameter and computes the tax
public int CalculateTax(int income)
{
int taxOwed = 0;
if (income < incomeLimit)
{
taxOwed = Convert.ToInt32(income * lowTaxRate);
}
if (income >= incomeLimit)
{
taxOwed = Convert.ToInt32(income * highTaxRate);
}
return taxOwed;
}
}
public class Taxpayer : IComparable
{
string socialSecurityNum;
int grossIncome;
int taxOwed;
// Use get and set accessors.
public string SocialSecurityNum
{
get
{
return socialSecurityNum;
}
set
{
socialSecurityNum = value;
}
}
// Use get and set accessors.
public int GrossIncome
{
get
{
return grossIncome;
}
set
{
grossIncome = value;
}
}
// Use read-only accessor
public int TaxOwed
{
get
{
return taxOwed;
}
}
// objects are comparable to each other based on tax owed.
int IComparable.CompareTo(Object o)
{
int returnVal;
Taxpayer temp = (Taxpayer)o;
if (this.taxOwed > temp.TaxOwed)
returnVal = 1;
else
if (this.taxOwed < temp.TaxOwed)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
public static void GetRates(int income)
{
int incomeLimit;
double lowRate;
double highRate;
char input;
Rates rates = new Rates();
Console.Write("Do you want default values (enter D) or enter your own (enter O)? ");
input = Convert.ToChar(Console.ReadLine());
switch (char.ToUpper(input)) // start switch
{
case 'D': // if the input latter is d or a D
rates.DoRates();
break;
case 'O': // if the input latter is o or an O
Console.Write("Enter the dollar limit ");
incomeLimit = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the low rate ");
lowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate ");
highRate = Convert.ToDouble(Console.ReadLine());
rates.DoRates(incomeLimit, lowRate, highRate);
rates.CalculateTax(income);
break;
default: Console.WriteLine("You entered and incorrect option"); // display this messages if the input was something other than D or O
break;
}
}
public static void Main()
{
// instantiate an array of five (5) Taxpayer objects.
Taxpayer[] taxPayer = new Taxpayer[5];
Rates taxRates = new Rates();
// Implement a for-loop that will prompt the user
// to enter the Social Security Number and gross income.
for (int x = 0; x < taxPayer.Length; ++x)
{
taxPayer[x] = new Taxpayer();
Console.Write("Enter Social Security Number for taxpayer {0} ", x + 1);
taxPayer[x].socialSecurityNum = Convert.ToString(Console.ReadLine());
Console.Write("Enter gross income for taxpayer {0} ", x + 1);
taxPayer[x].grossIncome = Convert.ToInt32(Console.ReadLine());
Taxpayer.GetRates(taxPayer[x].grossIncome);
taxPayer[x].taxOwed = taxRates.CalculateTax(taxPayer[x].grossIncome);
}
Thank you for the help everyone. I think I did get carried away a little while writing this code. After isolating the code with my issue I finally figured it out. Here is what I did in case anyone wants to see.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace assignment
{
public class Rates
{
public int incomeLimit; // income limit
public double lowTaxRate; // low tax rate
public double highTaxRate; // high tax rate
public int IncomeLimit { get { return incomeLimit; } }// read only property
public double LowTaxRate { get { return lowTaxRate; } } // read only property
public double HighTaxRate { get { return highTaxRate; } }// read only property
public Rates()
{
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
public Rates(int incomeLim, double lowRate, double highRate)
{
incomeLimit = incomeLim;
lowTaxRate = lowRate;
highTaxRate = highRate;
}
// CalculateTax method that takes an income parameter and computes the tax
public int CalculateTax(int income)
{
int taxOwed = 0;
if (income < incomeLimit)
{
taxOwed = Convert.ToInt32(income * lowTaxRate);
}
if (income >= incomeLimit)
{
taxOwed = Convert.ToInt32(income * highTaxRate);
}
return taxOwed;
}
}
public class Taxpayer
{
string socialSecurityNum = null;
int grossIncome = 0;
int taxOwed = 0;
// Use get and set accessors.
public string SocialSecurityNum { get {return socialSecurityNum;} set {socialSecurityNum = value;} }
// Use get and set accessors.
public int GrossIncome { get { return grossIncome; } set { grossIncome = value; } }
// Use read-only accessor
public int TaxOwed { get { return taxOwed; } }
public void GetRates(int income)
{
int incomeLimit = 0;
double lowRate = 0;
double highRate = 0;
char input;
Console.Write("Do you want default values (enter D) or enter your own (enter O)? ");
input = Convert.ToChar(Console.ReadLine());
switch (char.ToUpper(input)) // start switch
{
case 'D': // if the input latter is d or a D
Rates rates = new Rates();
taxOwed = rates.CalculateTax(income);
break;
case 'O': // if the input latter is o or an O
Console.Write("Enter the dollar limit ");
incomeLimit = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the low rate ");
lowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate ");
highRate = Convert.ToDouble(Console.ReadLine());
Rates myrates = new Rates(incomeLimit, lowRate, highRate);
taxOwed = myrates.CalculateTax(income);
break;
default: Console.WriteLine("You entered and incorrect option"); // display this messages if the input was something other than D or O
break;
}
}
public static void Main()
{
Taxpayer[] taxPayer = new Taxpayer[5];
Rates taxRates = new Rates();
Taxpayer myTaxpayer = new Taxpayer();
// Implement a for-loop that will prompt the user
// to enter the Social Security Number and gross income.
for (int x = 0; x < taxPayer.Length; ++x)
{
taxPayer[x] = new Taxpayer();
Console.Write("Enter Social Security Number for taxpayer {0} ", x + 1);
taxPayer[x].socialSecurityNum = Convert.ToString(Console.ReadLine());
Console.Write("Enter gross income for taxpayer {0} ", x + 1);
taxPayer[x].grossIncome = Convert.ToInt32(Console.ReadLine());
myTaxpayer.GetRates(taxPayer[x].grossIncome);
taxPayer[x].taxOwed = myTaxpayer.taxOwed;
}
// Implement a for-loop that will display each object
// as formatted taxpayer SSN, income and calculated tax.
for (int y = 0; y < taxPayer.Length; ++y)
{
Console.WriteLine("Taxpayer # {0} SSN: {1} income {2:C} Tax is {3:C}", y + 1, taxPayer[y].socialSecurityNum,
taxPayer[y].grossIncome, taxPayer[y].taxOwed);
}
}
}
}
I'll recommend to you to change your code, a more clean code and using betters OOP techniques.
You should check the class Taxpayer, specifically the method called GetRates().
in that method you create a object of type Rates, now, if you check the constructor of the class Rates
public Rates()
{
DoRates();
}
it calls the method Dorates() but without parameters, so, it will always call these DoRates method
public void DoRates() // class constructor that assigns default values
{
// set default values for limit, lowRate, and highRate
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
I'm surprised your compiler didn't complain. In Taxpayer.GetRates(int) you make a call to Rates.CalculateTax(int), which returns an int value. It doesn't get stored or returned anywhere, so I'm not sure what the purpose of the call is there. Also, since the object rates is attached to the static method GetRates(int), you're not changing any values in the object taxratesthat you use to calculate the tax. Finally, as has been suggested, your constructor sets default values. You could potentially add another constructor to take parameters. From there, you might want to make sure you change the values in the object you're using to calculate tax.
Occam's razor: keep it simple stupid. I think you're getting carried away with OOP. Simplify some things to make it work.
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();
}