[英]C# Method Continuously Loops
I am struggling to create a program that records the balance of a user.我正在努力创建一个记录用户余额的程序。 I have constructed four methods that are used to manage the user's method.我已经构建了四种用于管理用户方法的方法。 The methods include Main(), GetAmount(), Withdraw(), and Deposit.这些方法包括 Main()、GetAmount()、Withdraw() 和 Deposit。 Each method performs a specific operation on the data.每种方法对数据执行特定操作。 However, the GetAmount() method continuously loops without returning the amount inputted.但是,GetAmount() 方法会不断循环而不返回输入的金额。 I have attempted to use break statements to break out of the loop in the GetAmount() method however it continuously loops the entire method.我曾尝试使用 break 语句跳出 GetAmount() 方法中的循环,但它会不断循环整个方法。 I would like to check if the input is double.我想检查输入是否为双倍。 The input should be passed to the method that performs the operation chosen by the user.输入应传递给执行用户选择的操作的方法。
public static void Main() //THIS IS A COPY OF MY CODE
{
char transaction;
Console.WriteLine("Please enter a character 'W' to withdrawl, 'D' to deposit, 'P' to print balance, 'Q' to quit program)");
while (!char.TryParse(Console.ReadLine(), out transaction) )
{
Console.WriteLine("Please enter valid character: ");
}
double balance = 0;
double amount = GetAmount();
do
{
switch (transaction)
{
case 'w':
case 'W':
{
Withdrawal(amount, ref balance);
return;
}
case 'd':
case 'D':
{
Deposit(amount, ref balance);
return;
}
case 'p':
case 'P':
{
Print(balance);
return;
}
}
} while (char.ToUpper(transaction) != 'Q');
Console.WriteLine("You have typed Q to quit the program!");
Console.ReadLine();
}
public static double GetAmount()
{
double amount;
Console.WriteLine("Please enter amount to withdraw or deposit");
do
{
if (!double.TryParse(Console.ReadLine(), out amount))
{
Console.WriteLine("Please enter a valid amount.");
break;
}
if (amount < 0)
{
Console.WriteLine("Please enter a value that is > 0.");
break;
}
} while (amount > 0);
return GetAmount();
}
public static void Withdrawal(double amount, ref double balance)
{
balance -= amount - 1.5;
return;
}
public static void Deposit(double amount, ref double balance)
{
if (amount > 2000)
{
balance += amount * 1.01;
}
else
{
balance += amount;
}
return;
}
public static void Print(double balance)
{
Console.WriteLine("Your total balance is {0:C}.", balance);
return;
}
At the end of the GetAmount()
method, say:在GetAmount()
方法的末尾,说:
return amount;
instead of:代替:
return GetAmount();
The latter is incorrect because it is a recursive method call: https://en.wikipedia.org/wiki/Recursion后者不正确,因为它是递归方法调用: https : //en.wikipedia.org/wiki/Recursion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.