在我的while循环中,它会提示用户输入一个值,输入值后会运行某些方法。我遇到的问题是提示用户输入两次值(即要求输入A,B或X.用户输入值然后程序再次要求输入A,B或X而不执行正确的操作)。任何帮助它进入后操作都会很棒!
class output
{
static void Main(string[] args)
{
char userInput;
char upper;
Accounts myAccounts = new Accounts();
myAccounts.input();
Console.WriteLine("Enter an A to search account numbers");
Console.WriteLine("Enter a B to average the accounts");
Console.WriteLine("Enter X to quit the program");
Console.WriteLine("Enter an option --->");
userInput = Convert.ToChar(Console.ReadLine());
upper = char.ToUpper(userInput);
while (upper != 'X')
{
if (upper == 'A')
{
myAccounts.search();
Console.WriteLine("Enter an A to search account numbers");
Console.WriteLine("Enter a B to average the accounts");
Console.WriteLine("Enter X to quit the program");
Console.WriteLine("Enter an option --->");
userInput = Convert.ToChar(Console.ReadLine());
upper = char.ToUpper(userInput);
}
else if (upper == 'B')
{
myAccounts.average();
Console.WriteLine("Enter an A to search account numbers");
Console.WriteLine("Enter a B to average the accounts");
Console.WriteLine("Enter X to quit the program");
Console.WriteLine("Enter an option --->");
userInput = Convert.ToChar(Console.ReadLine());
upper = char.ToUpper(userInput);
}
else
Console.WriteLine("You entered an incorrect option, please select new option");
Console.WriteLine("Enter an A to search account numbers");
Console.WriteLine("Enter a B to average the accounts");
Console.WriteLine("Enter X to quit the program");
Console.WriteLine("Enter an option --->");
userInput = Convert.ToChar(Console.ReadLine());
upper = char.ToUpper(userInput);
}
}
}
答案 0 :(得分:2)
尝试重新格式化您的主要内容:
static void Main(string[] args)
{
char userInput;
char upper;
Accounts myAccounts = new Accounts();
myAccounts.input();
do
{
Console.WriteLine("Enter an A to search account numbers");
Console.WriteLine("Enter a B to average the accounts");
Console.WriteLine("Enter X to quit the program");
Console.WriteLine("Enter an option --->");
userInput = Convert.ToChar(Console.ReadLine());
upper = char.ToUpper(userInput);
if (upper == 'A')
{
myAccounts.search();
}
else if (upper == 'B')
{
myAccounts.average();
}
else
Console.WriteLine("You entered an incorrect option, please select new option");
}
while (upper != 'X')
}
它并不完美,但却是一个很好的起点。基本上,为什么你看到你的提示两次是因为你在进入while循环之前显示一次菜单,然后在执行操作之后再次显示。我提供的do while循环应该可以解决你的问题。