制作了一个控制台菜单,我需要一个计数器来计算错误的条目。如果点击5次,用户将返回到主菜单。我试图用while语句来做这件事,但它对我不起作用。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ConsoleApp3
{
internal class Program
{
private static readonly IDictionary<char, Action> InputDictionary = new Dictionary<char, Action>
{
{ '1', Information },
{ '2', Contact },
{ '3', Extra },
{ 'q', Exit },
};
static void Main()
{
MainWindow();
}
private static void MainWindow()
{
var inputWasProcessed = false;
while (inputWasProcessed == false)
{
DisplayMainMenu();
var wrongEntries = 0;
while (wrongEntries < 5)
{
if (0 < wrongEntries)
{
Console.WriteLine($"Wrong Entries: {wrongEntries}");
}
inputWasProcessed = ProcessUserInput(Console.ReadKey().KeyChar);
if (inputWasProcessed == false)
{
wrongEntries++;
}
else
{
break;
}
}
}
Console.ReadLine();
}
private static void DisplayMainMenu()
{
Console.Clear();
Console.WriteLine("Menu");
Console.WriteLine();
Console.WriteLine("1. Information");
Console.WriteLine("2. Contact");
Console.WriteLine("3. Extra");
Console.WriteLine("q. Exit");
}
private static bool ProcessUserInput(char selectedOption)
{
if (InputDictionary.TryGetValue(selectedOption, out var action))
{
Console.WriteLine();
Console.WriteLine();
action.Invoke();
return true;
}
Console.Clear();
Console.WriteLine("Input is wrong.");
Console.WriteLine("Try again.");
return false;
}
private static void Information()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Contact()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Extra()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Exit()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
#region For Demonstration Purposes Only
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetCurrentMethod() // https://stackoverflow.com/a/2652481/109941
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
#endregion
}
}