簡體   English   中英

如何從靜態void方法返回變量

[英]How to return variables from static void methods

我是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)

我更改了它們,因為我不知道如何從中返回可變金額
靜態void WithdrawAmount(int whichAccount)並將其用作靜態void DispenseCash(雙倍金額)中的參數。

我被迫使用這兩種方法,而不是使用一種較大的方法來解決問題。

這是我的代碼段,對它們進行了更好的解釋。 我只包括了相關部分以保持簡短。

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),則如何將int whichAccount和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;
      }
}

請記住,我根本無法更改方法標題。 但是我可以調用其中之一,也可以在方法內部調用新方法。 我嘗試了一些不同的嘗試,但是所有嘗試都失敗了。

正如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());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM