Thursday, 5 September 2013

How to return variables from static void methods, any help is appreciated.

How to return variables from static void methods, any help is appreciated.

I'm new to C# and strongly typed languages. I'm doing an assignment for
university and my program now works as intended. But, I changed 2 static
void method headings to have return types not realising doing so will
result in marks being deducted.
Current method headings
static bool DispenseCash(double amount, int whichAccount, bool
validAmount) and
static double WithdrawAmount(int whichAccount) must remain
What they need to be.
static void DispenseCash(double amount) and
static void WithdrawAmount(int whichAccount)
I changed them because I didn't know how to return the variable amount from
static void WithdrawAmount(int whichAccount) and use it as a parameter in
static void DispenseCash(double amount).
I am forced to use both methods rather than solve the issue using one
larger method.
Here is segments of my code to explain it all a little better. I have only
included the relevant parts to keep this short.
int whichAccount = int.Parse(Console.ReadLine());
do
{
double amount = WithdrawAmount(whichAccount);
validAmount = DispenseCash(amount, whichAccount, validAmount);
} while (validAmount == false);
//end of relevant method calls in main
static double WithdrawAmount(int whichAccount)
{
Console.Write("\nPlease enter how much you would like to withdraw: $");
double amount = double.Parse(Console.ReadLine());
return amount;
}
//end WithdrawAmount
In the DispenseCash method that follows if it is instead static void
DispenseCash(double amount) how can I pass int whichAccount and bool
validAmount into it and return a bool validAmount from it.
private static bool DispenseCash(double amount, int whichAccount, bool
validAmount)
{
int numOf20s;
int numOf50s;
double balenceMinusAmount = (accountBalances[whichAccount]) -
Convert.ToInt32(amount);
if((Convert.ToInt32(amount) >= 1) && (Convert.ToInt32(amount) % 50 == 0)
&& (balenceMinusAmount >= accountLimits[whichAccount]))
{
numOf50s = Convert.ToInt32(amount) / 50;
numOf20s = (Convert.ToInt32(amount) % 50) / 20;
Console.WriteLine("Number of 50's = {0}", numOf50s);
Console.WriteLine("Number of 20's = {0}", numOf20s);
accountBalances[whichAccount] = (accountBalances[whichAccount]) - amount;
return validAmount = true;
}
else
{
Console.WriteLine("Invalid entry");
return validAmount = false;
}
}
Remember I can not change the method headings at all. But I can call one
of them or new methods inside of the methods. I have tried a few different
things, but all attempts have failed. Any help is much appreciated,
thanks.

No comments:

Post a Comment