加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 只允许是或否作为答案

发布时间:2020-12-15 23:50:38 所属栏目:百科 来源:网络整理
导读:我是一个完整的新手,我遇到了一个小问题 我希望用户只能得到是或否作为答案. 这就是我提出的 static public bool askBool(string question){ try { Console.Write(question); return Console.ReadLine() == "y"; } catch (Exception) { throw new FormatExce
我是一个完整的新手,我遇到了一个小问题

我希望用户只能得到是或否作为答案.

这就是我提出的

static public bool askBool(string question)
{
    try
    {
        Console.Write(question);
        return Console.ReadLine() == "y";
    }
    catch (Exception)
    {
        throw new FormatException("Only y or n Allowed");
    }
}

问题是输入任何其他字母然后’y’将导致错误,我怎样才能最好地解决这个问题?

先感谢您.

编辑(来自评论问题)

try
{
    Console.Write(question);
    return int.Parse(Console.ReadLine());
}
catch (Exception)
{
    throw new FormatException("Please Enter a Number");
}

解决方法

Here the method will only return true or false if user has entered true or false.If user enters any word the loop will just continue to ask him for input until he enters y or n

您可以通过执行以下更改来尝试

static public bool askBool(string question)
    {
       bool boolToReturn = false;
       Console.Write(question);
       while (true)
       {
          string ans = Console.ReadLine();
          if (ans != null && ans == "y")
          {
              boolToReturn = true;
              break;
          }
          else if ( ans != null && ans == "n")
          {
              boolToReturn = false;
              break;
          }
          else
          {
              Console.Write("Only y or n Allowed");
          }
       }
       return boolToReturn;
    }`

Answer to second question:-

`

    public static int askInt(string question)
        {
           Int intToReturn = false;
           Console.Write(question);
           while (true)
           {
              string ans = Console.ReadLine();
              if (int.TryParse(and,out intToreturn))
                  break;
              else
                  Console.Write("Only number Allowed");
           }
           return intToReturn;
        }`

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读