简体   繁体   中英

Bank account with setters and getters

So i have a exercise where i need to do a bank account program. The pure goal is for me to understand the setters/getters and therefore is pretty simple.

I want to write my private int money; that is only accessible over my public get/set int Money; after i have that, i want to use a method, like withdraw, where i withdraw some of my money. Now i have the problem, when i do my withdraw method, it tells me: Since Konto.Konto(int) gives void back, there can be no return. (Its not the word for word explanation, its my translation.

I have never set anything to void, so i don't see where my problem is. Thank you in advance for helping me.

Edit: My end goal is that if i press 1 i can set the amount of money i withdraw and my system prints me the value i have left. So i "feed" my method a withdraw number, said number gets substracted from my initial value and it returns me the value i have left.

namespace ConsoleApp1
{
    class Konto
    {
        private int money;
        public int Money
        {
            get
            {
                return this.money;
            }
            set
            {
                money = value;
            }

        }

        public Withdraw(int money)
        {
            return Money - money;
        }

    }
}

You're missing the return type on your Withdrawal method. It should be

public int Withdrawal(int money)
{
   //you weren't setting the money variable to the new amount
   Money -= money;
   return Money;
}

In C# only the class constructor doesn't need a return type. So

class Konto
{
   public Konto()
   {...}
}

Is valid but all other methods needs to have a return type. Also, just as a matter of style/clean up. You don't need the private backing field. If you want to initialize the amount in the account and only change it through withdrawal and deposit method you can do something like this.

class Konto
{
   public int Money {private set; get;}
   public Konto(int initialAmount)
   {
       Money = initialAmount;
   }

   public int Withdrawal(amount)
   {
      Money -= amount;
      return Money;
   }

   public void Deposit(int amount)
   {
      Money += amount;
   }
}

In this code Money can only be set from inside the class through methods that you create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM