问题描述
我有一个名为 private
的 RentingOrBuying();
方法,用于收集有关房地产价格和利率的信息。我想创建另一个 private
方法来计算每月房屋贷款还款额,但我需要 RentingOrBuying()
中的信息。
我尝试过使用 get 和 set 方法,但初始化似乎不起作用。也许我做错了。任何帮助表示赞赏。我正在调用主类中的所有方法。值得让他们 private
还是我应该让方法 public
。你会怎么做?
//this method uses the information gathered in RentingOrBuying and calculates the monthly home loan repayment
private static void CalculateMonthlyLoanAmount()
{
//accumulated amount = propertyPrice(1 + interestRate)^monthsToRepay
double repaymentAmount = propertyPrice(1 + interestRate);
}
//A method that asks whether the user is buying or renting accommodation and gathers necessary information
private static void RentingOrBuying()
{
Console.WriteLine("Are you going to be renting accommodation or buying a property? \n Please enter either [rent] or [buy]");
//variable to store user input
string buyingRenting = Console.ReadLine();
if (buyingRenting.ToLower() == "rent")
{
Console.WriteLine("We see you want to rent,please can you enter the monthly rental amount: ");
//variable that stores the monthly rental amount.
double monthlyRental = double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("So you've chosen to buy,I will just need the following ionformation:");
Console.WriteLine("Please enter the purchase price of property: ");
//variable stores the price of the property the user wants to buy
double propertyPrice = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the total deposit: ");
//variable stores the total deposit
double totalDeposit = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the interest rate (percentage): ");
//variable store the interest rate in percentage form
int interestRate = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter the number of months to repay: ");
//variable stores the amount of months to repay
int monthsToRepay = Int32.Parse(Console.ReadLine());
}
}
解决方法
您应该将任何需要的变量作为输入参数,并返回任何计算结果,即
private static double CalculateMonthlyLoanAmount(double interestRate,double propertyPrice)
{
// do whatever calculation you need do to here
// return the result
return result;
}
更复杂的场景将涉及将变量封装在一个类中,以避免在多次调用一个方法或多个方法共享许多变量时需要指定它们。