Simple Account Class

Simple Account Class

Programming Assignment –OOP
This assignment has multiple requirements
Program Requirements:
1. Modify the program below by adding a method to PiggyBank for withdrawing money.
2. Use logic to determine if the value user entered in the main program is a negative
value. If the value entered is negative, call the Withdraw method you created, otherwise
use the addMoney method.
3. Handle any errors that may occur, such as the user entering values other than numbers.
When handling the error, display a message to the user that the value they entered was
invalid.
4. Modify the Withdraw function you created to prevent the PiggBankvalue from going below 0.
using System;
class PiggyBank
{
int value;
public void getValue()
{
Console.WriteLine(value);
}
public void addMoney(Int16 howmuch)
{
value = value + howmuch;
}
}
class Program
{
static void Main(string[] args)
{
PiggyBankmyBank = new PiggyBank();
Int16 dollars;
do {
Console.WriteLine(“Enter a value, or 0 to exit.”);
dollars = Convert.ToInt16(Console.ReadLine());
myBank.addMoney(dollars);
myBank.getValue();
} while (dollars != 0);
}
} 

Solution 

using System;

classPiggyBank

{

int value;

public void getValue()

{

Console.WriteLine(value);

}

public void addMoney(Int16 howmuch)

{

value = value + howmuch;

}

public void withdraw(Int16 howmuch)

{

value = value – howmuch;

// BONUS: do not draw to a negative value

if (value < 0)

{

value = 0;

}

}

}

public class Program

{

public static void Main(string[] args)

{

PiggyBankmyBank = new PiggyBank();

Int16 dollars;

do

{

Console.WriteLine(“Enter a value, or 0 to exit.”);

if (!Int16.TryParse(Console.ReadLine().Trim(), out dollars))

{

Console.WriteLine(“error: the value you entered is invalid.”);

}

else if (dollars < 0)

{

myBank.withdraw((Int16)(-dollars));

}

else

{

myBank.addMoney(dollars);

}

myBank.getValue();

}

while (dollars != 0);

}

}