C# methods and parameters - c#

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

Related

Accessing a variable in a private method from another private method. 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.

Adding user input into equation through a variable possible? (C#)

I apologize if this is a really simple solution...
So I'm trying to get an Ending Balance from 4 inputs, those being
Starting Balance
Number of months that have elapsed
User Specified yearly interest rate
and a optional monthly contribution that the user can put in. This is what I would imagine the equation to be
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
Everything is fine until the compiler states that Use of unassigned local variable 'contribution' This really confuses me because at the comment at the top of the code I have stated that contribution will be an int.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
// Constant for the monthly interest rate.
const decimal INTEREST_RATE = 0.005m;
// Local variables
decimal balance; // The account balance
int months; // The number of months
int contribution;
int count = 1; // Loop counter, initialized with 1
decimal yearly;
// Get the starting balance.
if (decimal.TryParse(txtStartBalance.Text, out balance))
{
// Get the number of months.
if (int.TryParse(txtMonths.Text, out months))
{
// Get the yearly interest rate
if (decimal.TryParse(txtYearly.Text, out yearly))
{
//Get monthly contribution
if (int.TryParse (txtMonthly.Text, out contribution));
}
// The following loop calculates the ending balance.
while (count <= months)
{
// Add this month's interest to the balance.
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
// Display this month's ending balance.
if (rdoEnglish.Checked == false)
lstDetails.Items.Add("ʻO ka pale hope " + "no ka mahina " + count + " ʻO " + balance.ToString("c"));
else
lstDetails.Items.Add("The ending balance for " + "month " + count + " is " + balance.ToString("c"));
// Add one to the loop counter.
count = count + 1;
}
// Display the ending balance.
txtEnding.Text = balance.ToString("c");
Again thank you for taking the time to help me.
This really confuses me because at the comment at the top of the code I have stated that contribution will be an int.
Yes but you have not assigned a value to the variable in at least one path your code can take. (Specifically if int.TryParse (txtMonthly.Text, out contribution)); fails) And then you try to use contribution in the line:
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
You need to assign a value to contribution before you use it. Think about what contribution is supposed to represent and assign it to a value accordingly
Try to declare your variables Like below:
decimal.TryParse(txtStartBalance.Text, out decimal balance);
it is better to make a checkbox for the contribution field (txtMonthly) and set its visibility to Checkbox.checked property so if the user wants to set the optional contribution value, has to check the checkbox to write it down.
Also using that ifs in your code is useless until you throw Exceptions when those TryParse methods retrun false and warn the user to try again with right inputs.

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

How to get decimal remainder of two numbers divided?

So I am trying to make a script where the user inputs the number of miles they need to travel and the miles per hour they are traveling and the script outputs the hours and minutes leftover that they must travel. I've been trying to use % to find the remainder of the miles traveled/MPH but it outputs the wrong number. Is there anyway to only get the decimal from two divided numbers? For example, if I do 100/65 I get the output of about 1.538, I want to only use the 0.538. But when I use 100%65 I get 35. Here is my current script for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Travel Time Calculator");
string answer;
//creates variable for the answer
do
//creates loop to continue the application
{
string grade;
//Console.WriteLine(100-(int)((double)100/65)*65);
Console.WriteLine(" ");
Console.Write("Enter miles: ");
Decimal val1 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.Write("Enter miles per hour: ");
Decimal val2 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.WriteLine(" ");
Console.WriteLine("Estimated travel time");
Console.WriteLine("Hours: " + (((int)val1 / (int)val2)));
//converts values to integers and divides them to give hours traveled
//double floor1 = Math.Floor(((double)val1/(double)val2));
Console.WriteLine("Minutes: " + (Decimal.Remainder((decimal)val1, (decimal)val2)));
//converts values to double and gets the remainder of dividing both values to find minutes
Console.WriteLine();
//enters one line
Console.Write("Continue? (y/n): ");
answer = Console.ReadLine();
//the string is equal to what the user inputs
Console.WriteLine();
}
while (answer.ToUpper() == "Y");
//if y, the application continues
}
}
100/65 is an integer division. What you need is
double d = (100d / 65) % 1;
This will give you 0.53846153846153855
If you want hours and minutes from the initial values then this should do it for you (you may need some explicit casts in there, this is untested)
var result = va1 / val2;
var hours = Math.Floor(result);
var minutes = (result - hours) * 60;

Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED

I have an application that calculates your gold per minute farmed.
I want to make an error report that wouldn't allow you to insert any text in the console input where yous hould insert the time and gold(as shown in code below) and show some error message if you do and let you redo the insertion (some sort of loop or if/else thing ...)
Hope i made my self clear,thou I'm new to this... so i hope you understand.
Here is my code so far :
-------------------------------//////////
Update on question because i didn't want to make a new question for the same code :
How do i transform in this code my hours into minutes,the float calculation of 1.2 hours will calculate into 72 minutes not 80.(i've put comment below in code where the problem is)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YourGold
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to YourGold App! \n------------------------");
Console.WriteLine("Inesrt your gold: ");
int gold = int.Parse(Console.ReadLine());
Console.WriteLine("Your gold is : " + gold);
Console.WriteLine("Inesrt your time(In Hours) played: ");
float hours = float.Parse(Console.ReadLine());
int minutes = 60;
float time = (float)hours * minutes; // Here the calculation are wrong...
Console.WriteLine("Your total time playd is : " + time + " minutes");
float goldMin = gold / time;
Console.WriteLine("Your gold per minute is : " + goldMin);
Console.WriteLine("The application has ended, press any key to end this app. \nThank you for using it.");
Console.ReadLine();
}
}
}
Thank you!
Instead of using int.Parse, you can use int.TryParse, and print a message:
int gold;
while(!int.TryParse(Console.ReadLine(), out gold))
{
Console.WriteLine("Please enter a valid number for gold.");
Console.WriteLine("Inesrt your gold: ");
}
This allows you to re-prompt and handle errors correctly.
In console application you can't control text input (no keypressed event to handle).
This could be a solution
Console.WriteLine("Inesrt your gold: ");
int gold;
while(!int.TryParse(Console.ReadLine(),out gold)){
Console.WriteLine("Please provide a valid gold value");
}
Console.WriteLine("Your gold is : " + gold);

Categories