【问题标题】:how to check if string or int C# [duplicate]如何检查字符串或int C# [重复]
【发布时间】:2017-07-14 19:39:06
【问题描述】:

我试图弄清楚我做错了什么。我希望代码的第一行提出一个问题,并希望 if 语句检查字符串或不在 1-12 之间的数字。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Class1
    {

        public void checknumber()
        {

            string result;
            int input = result;
            Console.WriteLine("Please enter the month in numerical value (1-        12)");
            Console.Write(result);

            if (input < 1 && input > 12)
            {
                Console.WriteLine("Please close the program, run the program     again, and input  number between 1-12");

            }
        }
    }

}

【问题讨论】:

  • “检查字符串或数字”是什么意思。您只是想检查它是否是 1 到 12 之间的数字,对吗?
  • 你好约瑟夫。目前此代码甚至无法编译。就您做错的事情而言,您是否看到错误消息?你还有其他尝试展示吗?我认为您可以做更多的事情来自己调试。为了给出一些指示,您当前没有从控制台读取输入并将其分配给任何东西。这需要通过Console.ReadLine() 来实现。将其分配给result。然后,看看int.TryParse
  • 你可以试试IsNumber
  • 您也可以使用正则表达式。 bool isNumber = Regex.IsMatch(result, @"^\d+$")

标签: c# if-statement int tostring


【解决方案1】:

尝试使用“Int32.TryParse”。如果输入的字符不是数字,则返回 false。

Console.WriteLine("Please enter the month in numerical value (1-        12)");
if (!Int32.TryParse(Console.ReadLine(), out result))
   {
    result = 0;
   }
    if (result < 1 && result > 12)
     {
       Console.WriteLine("Please close the program, run the program     again, and input  number between 1-12");
      }

【讨论】:

  • 如果您包含更多 OP 的原始代码,那就太好了。这将帮助 OP 了解它是如何适应的。
  • 开发者可以自己添加条件。不过也加了他的条件。
  • OP 似乎没有那么有经验。这就是我建议它的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2020-08-27
  • 2011-02-20
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
相关资源
最近更新 更多