如何从静态void方法返回变量

时间:2013-09-06 01:32:30

标签: c# return scope void

我是C#和强类型语言的新手。我正在为大学做作业,我的课程现在按预期工作。但是,我更改了2个静态void方法标题,使得返回类型没有意识到这样做会导致标记被扣除。

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)

我更改了它们,因为我不知道如何从中返回变量     static void WithdrawAmount(int whichAccount)     并将其用作参数     static void DispenseCash(double amount)。

我被迫使用这两种方法,而不是使用一种更大的方法解决问题。

以下是我的代码段,可以更好地解释它。我只包括相关部分以保持简短。

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

在后面的DispenseCash方法中,如果它是静态的,则为void DispenseCash(double amount)如何将intAccount和bool validAmount传递给它并从中返回bool validAmount。

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

请记住,我根本无法更改方法标题。但我可以在方法中调用其中一个或新方法。我尝试了一些不同的东西,但所有尝试都失败了。

1 个答案:

答案 0 :(得分:2)

正如jdphenix所说,我不确定为什么要这样做。它违背了基本的编程原则。也许我们不了解手头问题的全部背景。

我能想到的唯一方法就是在应用程序中使用静态变量。

private static double withdrawalAmount;
private static int selectedAccount;
private static bool isValidAmount;

然后在您所需的方法中使用这些,例如:

public static void WithdrawAmount(int whichAccount)
    {
        Console.Write("\nPlease enter how much you would like to withdraw: $");
        withdrawalAmount = double.Parse(Console.ReadLine());
    }
相关问题