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 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!