【问题标题】:Returning from input() method, in while loop within same method从 input() 方法返回,在同一方法内的 while 循环中
【发布时间】:2013-07-13 19:57:54
【问题描述】:
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”输入名称的次数。

【问题讨论】:

  • 在循环中输入名称而不是递归

标签: c# .net loops refactoring


【解决方案1】:

您正在递归调用input()。如果你说'y' 几次然后'n' 它将不得不在每次调用input() 时返回堆栈。每次调用输入时,您都必须按“n”或“N”。

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

【讨论】:

  • 感谢您的回复。但是你能详细说明一下吗?
  • 有没有办法直接退出递归调用的方法?
  • 不在 C# 中 - 你需要尾递归。
  • 谢谢,我也试试。
【解决方案2】:

在循环中输入名称而不是递归调用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);
}

【讨论】:

  • 好一个。看不到如果:-)
  • 感谢您的帮助。
  • 第二种编码方式很好,我以后会尝试使用这种技术。
猜你喜欢
  • 2021-12-29
  • 2013-11-06
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 2015-01-09
  • 1970-01-01
相关资源
最近更新 更多