0
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”我们输入名称的次数。

4

2 回答 2

1

您正在递归调用input(). 如果您说'y'几次,那么'n'每次调用input(). 每次调用输入时,您都必须按“n”或“N”。

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

于 2013-07-13T11:39:38.953 回答
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);
}
于 2013-07-13T11:44:36.917 回答