从input()方法返回,在while循环中使用相同的方法

时间:2013-07-13 11:30:11

标签: c# .net loops refactoring

namespace ClassesnObject
{
class Program
{

    public class myClass
    {
        string val;
        public static int val2 = 0;            

        public void bottle(string name)
        {
            val = name;
            val2++;
        }            

    }
    static ConsoleKeyInfo readkey = new ConsoleKeyInfo();
    static myClass myObj = new myClass();
    static void input()    //This is the problematic method
    {
        string name;
        bool con = true;   
        Console.WriteLine("Enter name: ");
        name = Console.ReadLine();
        myObj.bottle(name);
        while (con)
        {                
            Console.WriteLine("Want to enter more name(Y/N)? ");                
            readkey = Console.ReadKey();
            if (readkey.KeyChar == 'Y' || readkey.KeyChar == 'y') input();
            else if (readkey.KeyChar == 'N' || readkey.KeyChar == 'n') return;//Problem
            else continue;
        }
    } 
    static void Main(string[] args)
    {
        input();
        Console.WriteLine("No. of entries are: " + myClass.val2);
        Console.ReadLine();                    
    }
}

当我在input()方法中时,在while循环中按'Y'或'y'完成工作,但'N'或'n'不起作用。 似乎在按下'N'或'n'时,在我们输入名字的时间按'N'或'n'之前它不会返回。

2 个答案:

答案 0 :(得分:1)

您递归调用input()。如果您'y'几次'n',则必须在每次拨打input()时向下走回堆栈。每次调用输入时,您都必须按'n'或'N'。

摆脱一些方便的挥动ifs可能会有所帮助......

答案 1 :(得分:1)

在循环中输入名称而不是递归调用Input()方法,并使用ConsoleKey验证用户输入:

static void Input()
{
    ConsoleKey key;
    do
    {
        Console.WriteLine("Enter name: ");
        string name = Console.ReadLine();
        myObj.bottle(name);            

        do
        {
            Console.WriteLine("Want to enter more name(Y/N)? ");
            key = Console.ReadKey().Key;
        } while (key != ConsoleKey.Y && key != ConsoleKey.N);

    } while (key == ConsoleKey.Y);
}

更进一步,我将内循环和循环体提取到自己的方法中。这将向读者显示您的代码的意图。看 - 这段代码描述了究竟发生了什么:

static void EnterNames()
{        
    do
    {
       EnterName();
    } 
    while (WantToEnterMoreNames());
}

static void EnterName()
{
    Console.WriteLine("Enter name: ");
    string name = Console.ReadLine();
    myObj.bottle(name);   
}

static bool WantToEnterMoreNames()
{        
    do
    {            
        Console.WriteLine("Want to enter more name(Y/N)? ");

        switch (Console.ReadKey(true).Key)
        {
            case ConsoleKey.Y: return true;
            case ConsoleKey.N: return false;
            default:
                continue;
        }
    } 
    while (true);
}