Accessing a variable in a private method from another private method. C# - c#

I have a private method named RentingOrBuying(); that gathers information about the property price and interest rate. I want to create another private method that calculates the monthly home loan repayment but I need the information in RentingOrBuying().
Ive tried using get and set methods but the initialization doesn't seem to work. Maybe I did it wrong. Any help is appreciated. I am calling all the methods in the main class. Is it worth leaving them private or should I be making the methods public. How would you go about this?
//this method uses the information gathered in RentingOrBuying and calculates the monthly home loan repayment
private static void CalculateMonthlyLoanAmount()
{
//accumulated amount = propertyPrice(1 + interestRate)^monthsToRepay
double repaymentAmount = propertyPrice(1 + interestRate);
}
//A method that asks whether the user is buying or renting accommodation and gathers necessary information
private static void RentingOrBuying()
{
Console.WriteLine("Are you going to be renting accommodation or buying a property? \n Please enter either [rent] or [buy]");
//variable to store user input
string buyingRenting = Console.ReadLine();
if (buyingRenting.ToLower() == "rent")
{
Console.WriteLine("We see you want to rent, please can you enter the monthly rental amount: ");
//variable that stores the monthly rental amount.
double monthlyRental = double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("So you've chosen to buy, I will just need the following ionformation:");
Console.WriteLine("Please enter the purchase price of property: ");
//variable stores the price of the property the user wants to buy
double propertyPrice = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the total deposit: ");
//variable stores the total deposit
double totalDeposit = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the interest rate (percentage): ");
//variable store the interest rate in percentage form
int interestRate = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter the number of months to repay: ");
//variable stores the amount of months to repay
int monthsToRepay = Int32.Parse(Console.ReadLine());
}
}

you should take any variables needed as input parameters, and return any results from the calculations, i.e.
private static double CalculateMonthlyLoanAmount(double interestRate, double propertyPrice)
{
// do whatever calculation you need do to here
// return the result
return result;
}
More complex scenarios would involve encapsulating the variables in a class, to avoid needing to specify them if you call a method multiple times, or multiple methods share many of the variables.

Related

C#; Not all code paths return a value

I have been looking for a post that can actually help me figure this out, the thing is I am very new, as in within my first 30 days of seriously learning to code. Here is my code;
class Program
{
static void Main(string[] args)
{
string name; //Employee Name added to nameList
double payRate; //Employee Pay Rate added to rateList
double hoursWorked; //Integer associated with how many hours the employee worked, multiplied by payRate
bool addMore;
List<string> nameList = new List<string>();
List<double> rateList = new List<double>();
List<double> hWorkedList = new List<double>();
}
public static object PayRollMethod(string name, double payRate, double hoursWorked, bool addMore, List<string> nameList, List<double> rateList, List<double> hWorkedList)
{
Console.Write("Enter employee name: ");
name = Console.ReadLine();
nameList.Add(name); //adds the name entered to the namesList
Console.Write("What is the pay rate for this employee: ");
payRate = Convert.ToDouble(Console.ReadLine());
rateList.Add(payRate); //adds the payRate to the rateList, as a double
Console.Write("How many hours did the employee work? ");
hoursWorked = Convert.ToDouble(Console.ReadLine());
hWorkedList.Add(hoursWorked);
Console.Write("Do you need to add any other employees? Y or N");
addMore = Convert.ToBoolean(Console.ReadLine());
Console.ReadKey(); //holds the console open after the program finishes
}
}
When I try and run it I get an error with the PayRollMethod giving me the error listed.
I think that the issue is the boolean at the bottom (addMore), I have that as it will signal the program to either restart the user input section, or prompt the user to either exit or edit an entry. I am still trying to figure out the best way to implement the loop, so I haven't typed up that part yet.
Thanks in advance for the help.
You declared PayRollMethod with an object return type, that means you must return an object instance before you leave the method. If you don’t want to return any value, then you can declare the method with void return type.

Errors in library fee code using multiple methods

I'm making a library program that asks for users to input the amount of books checked out and the amount of days they are over due. If its under or equal to 7 days they are charge 10 cents for each book over due after 7 days its 20 cents for each book. We are supposed to use more than one method and I get two errors:
Use of unassigned local variable 'totalCharge'
There is no argument given that corresponds to the required formal parameter 'daysOverdue' of Program.charge(double,double,double)'
I think I know what the first error means but I thought I already declared it a variable in the first line.
Here's the code so far:
static void Main(string[] args){
double totalCharge;
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are
overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your total charge for {0} days overdue is {1}.",
daysOverdue, totalCharge.ToString("C"));
Console.ReadKey();
totalCharge = charge();
}
private static double charge (double daysOverdue, double booksChecked,
double totalCharge)
{
if (daysOverdue <= 7)
{
return totalCharge = booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + (booksChecked) * (daysOverdue - 7)
* (.20);
}
}
}
}
Your code has a number of problems, which I'll review here. My corrections are at the end of this answer. I recommend putting your code and mine side by side and reviewing the differences carefully.
First, you cannot read the value out of a variable before you have assigned a value. You must assign something to it first.
You need to call charge(...) before printing out the value of totalCharge.
Second, you don't need to pass the value of totalCharge to your charge(...) method: it returns the total charge! So remove that parameter entirely.
Third, you need to pass parameters to the charge method.
Fourth, you had some formatting problems. Please review my code to see how I've formatted my code differently. If a line of code is continued onto the next line, use indentation to reflect this. According to C# conventions, function names should be capitalized.
Lastly, this isn't necessarily a problem, but it doesn't look 'right': in two places, you are assigning Convert.ToInt32(...) to a double. Why? Those should be integers.
static void Main(string[] args)
{
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
// assign before printing out value
// pass the two parameters into the function
double totalCharge = Charge(daysOverdue, booksChecked);
Console.WriteLine("Your total charge for {0} days overdue is {1:C}.",
daysOverdue,
totalCharge);
Console.ReadKey();
}
private static double Charge(double daysOverdue, double booksChecked)
{
if (daysOverdue <= 7)
{
return booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + booksChecked * (daysOverdue - 7) * (.20);
}
}

Is my program calculating wrong? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So in my C# class, I was asked to;
Write a program that computes the amount of money the computer club will receive from proceeds of their granola bar sales project. Allow the user to enter the number of cases sold and the sale price per bar.Each case contains 12 bars; each case is purchased at $5.00 per case from a local vendor.The club is required to give the student government association 10% of their earnings. Display their proceeds formatted with currency. Write appropriate methods for your solution.
I wrote the program but I am pretty sure the math is not adding up (unless I am screwing up the calculations that I am plugging into my calculator.
Here is my code.
using System;
namespace GranolaBars
{
class Granola
{
static void Main(string[] args)
{
// Give user info on program
Console.WriteLine("The Computer Club buys the cases at $5.00 a case");
Console.WriteLine("The studdent government gets 10% of profit");
Console.WriteLine("Total made from sell is number of cases sold minus 10%");
// Declare the variables
int casesSold;
decimal pricePerBar;
decimal profit;
decimal proceeds;
decimal finalOutCome;
// Set the variables values
casesSold = GetCasesSold();
pricePerBar = GetPricePerCase();
profit = GetProfit(casesSold, pricePerBar);
proceeds = GetProceeds(profit);
finalOutCome = GetFinalOutCome(proceeds, profit);
// The output from the program
Console.WriteLine("The amount cases of sold was: {0} ", casesSold);
Console.WriteLine("The price per bar was {0:C}: ", pricePerBar);
Console.WriteLine("The gross profit is: {0:C}: ", profit);
Console.WriteLine("The student government fees are: {0:C} ", proceeds);
Console.WriteLine("The income minus the student government fees is: {0:C} ", finalOutCome);
Console.ReadKey();
}
public static int GetCasesSold()
// Method that gets the total number of cases sold
{
int CSold;
Console.Write("Enter the number of cases sold: ");
CSold = int.Parse(Console.ReadLine());
return CSold;
}
public static decimal GetPricePerCase()
// Method that gets the price per case of garnola bars
{
decimal PerBar;
Console.Write("Enter the price per bar: ");
PerBar = decimal.Parse(Console.ReadLine());
return PerBar;
}
public static decimal GetProfit(int CasesSold, decimal PricePerBar)
// Method to get the Profit
{
decimal PriceofCase = 5.00M;
decimal Earnings;
Earnings = ((PricePerBar * 12) - PriceofCase);
return Earnings;
}
public static decimal GetProceeds(decimal Profit)
// Method to get the Proceeds
{
decimal StudentGovFunds = .10M;
return (Profit * StudentGovFunds);
}
public static decimal GetFinalOutCome(decimal Proceeds, decimal Profit)
// Method to calculate the final total made from selling granola pars
{
return (Profit - Proceeds);
}
}
Is my program calculating correctly or am I missing what would make it calculate correctly?
This seems to be a problem
I mean you need to times how many cases are sold at least at some point
public static decimal GetProfit(int CasesSold, decimal PricePerBar)
// Method to get the Profit
{
return (((PricePerBar * 12) - PriceofCase) * CasesSold);
}
output
The Computer Club buys the cases at $5.00 a case
The studdent government gets 10% of profit
Total made from sell is number of cases sold minus 10%
Enter the number of cases sold: 2
Enter the price per bar: 10
The amount cases of sold was: 2
The price per bar was $10.00:
The gross profit is: $230.00:
The student government fees are: $23.00
The income minus the student government fees is: $207.00

C# simple console app stock trading

Hi I’m new to C# and I am trying to build a very simple stock tracking console application where a user inputs some info about a stock and the program saves and uses the input. I’ve been going through online tutorials but I cannot seem to put it all together.
I want to ask a user to choose whether they want to sell a stock, buy a stock, or exit the program. If they choose buy or sell a stock the program will ask them to enter the stock ticker, amount of stock purchased and price paid.
In this case I want the user to be able to continue to buy stock or sell stock until they choose to exit the application. The program should track the total amount of stock the user has for each ticker. For example, the user can input they purchased 100 shares of APPL stock on 2/1/12, then enter they purchased an additional 50 shares of APPL stock on 2/15/12, and then sold 25 shares of APPL stock on 3/1/12.
The program will track the info and when the user chooses to exit, the program will output how many shares they have left. In the above example they have 125 shares left.
Eventually I want to turn this into a real-time stock trading program, but for now I'm just taking baby steps.
I have include the code I have written so far below. I don't understand the best way to handle the user input.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace StockTracker
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Welcome to the Stock Tracker");
Console.WriteLine("--------------------------------");
Console.WriteLine("Please choose from the following options:");
Console.WriteLine("1) Buy Stock, 2) Sell Stock, 0) Exit");
ArrayList Array1 = new ArrayList();
ArrayList Array2 = new ArrayList();
string userValue = Console.ReadLine();
string message = "";
double price;
int amount;
string stockTicker;
switch (userValue)
{
case "1":
Console.WriteLine("Enter ticker to buy:");
stockTicker = Console.ReadLine();
Array1.Add(stockTicker);
Console.WriteLine("Enter stock price");
price = double.Parse(Console.ReadLine());
Array1.Add(price);
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
Array1.Add(amount);
Console.WriteLine("***Stock Purchased***");
break;
case "2":
//message = "Enter stock ticker to sell";
Console.WriteLine("Enter stocker ticker to sell");
stockTicker = Console.ReadLine();
Array2.Add(stockTicker);
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
Array2.Add(amount);
Console.WriteLine("***Stock Sold***");
break;
case "0":
Console.WriteLine("Good Bye!");
return;
default:
message = "Invalid entry";
break;
}
Console.Write(message);
Console.ReadLine();
Console.WriteLine();
} //while (userValue != "0");
}
}
}
You need to think about what your requirements are exactly. Do you need to track every trade? Or just the total of each stock? Do you want this information to be persistent?
If you just what to keep track of the total number of each stock, I'd suggest using a Dictionary instead of your ArrayLists. Something like this:
Dictionary<string,int> myStocks = new Dictionary<string,int>();
//....
case "1":
Console.WriteLine("Enter ticker to buy:");
stockTicker = Console.ReadLine();
Console.WriteLine("Enter stock price");
price = double.Parse(Console.ReadLine());
Console.WriteLine("Enter Quantity");
amount = int.Parse(Console.ReadLine());
int currAmount = 0;
myStocks.TryGetValue(stockTicker,out currAmount);
myStocks[stockTicker] = currAmount + amount;
Console.WriteLine("***Stock Purchased***");
break;
If you really need to track both the name and amounts separately, you should create a class (call it Trade) that has properties for stock symbol, amount, price, date, etc and store those in a List<Trade>.

C# methods and parameters

currently I am studying in Sweden an online course Fundamental programming in C# and I have a problem with one of the examples. In the lecture there is an example of Methods and parameters and there is a mistake in the coding so when I want to try it and see what it does it doesn't work. I have written an email to the lecturer couple of days ago but he is not responding.
Here is the code:
I have two classes. First is Account.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Classes_Objects_2
{
class Account
{
public double Balance = 0;
public void ShowMessage()
{
Console.WriteLine("Welcome to the Account Book!");
}
// Method Deposit.
public double Deposit(double depositAmount)
{
// You get a 5% bonus.
return depositAmount * 1.05;
}
}
}
And here is the second code which returns 2 errors:
Class is called Accounts.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Classes_Objects_2
{
class Accounts
{
static void Main(string[] args)
{
Account myAccount = new Account();
myAccount.ShowMessage();
Console.WriteLine("Your balance is " + myAccount.Balance);
Console.Write("Enter the deposit amount: ");
double newBalance = myAccount.Deposit(double.Parse(Console.ReadLine()));
newBalance = amountDep;
Console.WriteLine("Your balance becomes " + newBalance);
Console.Write("Enter the next deposit amount: ");
newBalance = myAccount.Deposit(double.Parse(Console.ReadLine()));
newBalance = amountDep;
Console.WriteLine("Your balance becomes " + newBalance);
}
}
}
When user enters 100 as deposit, he gets 105 with the deposit and then when he enters 200 he gets 315. That is output I am aiming for and it should work according to the lecture.
I get error in the Accounts class because of the amountDep, it ssays it is not recognized, which is true but I have no idea how to fix this. Can you please help me figure this one out so I can continue studying?
Thank you!
you have not instantiated amountDep or given it a value
ad something like
double amountDep = 0;
or a value of choice
You could declare the variable:
double amountDep = 1234;
You need to change your Deposit method to include "Balance += depositAmount * 1.05" to increment the account balance and store the deposit. Use the Balance field of your account class to retrieve the current balance in your Main method (e.g. Console.WriteLine("Balance: " + myAccount.Balance);
Notes: You should not use public fields, but class properties. Fields should not be named in upper case (like "Balance"), but "balance", or "_balance", or "mBalance".
Good luck!
I think the amountDep is not necessary. It is nowhere declared anyway.
It could be removed, since the assignment of newBalance is done above the assignment of amountDep.
Just a small textual mistake I guess!
Simply remove these two lines :
newBalance = amountDep;
It's not clear what was intended here, and there are n other mentions of the non-existent variable amountDep, so I'd say in order to get compiling code just remove those two lines and carry on.
As far as I can see, the balance does not change after you execute Deposit method. So my guess will be, that amountDep should be added to your account's balance, like this:
double amountDep = myAccount.Deposit(double.Parse(Console.ReadLine()));
double newBalance = myAccount.Balance += amountDep;
Console.WriteLine("Your balance becomes " + newBalance);
Console.Write("Enter the next deposit amount: ");
amountDep = myAccount.Deposit(double.Parse(Console.ReadLine()));
myAccount.Balance += amountDep;
Console.WriteLine("Your balance becomes " + newBalance);

Categories