2017-02-24 171 views
0

我试着找出我做错了。我想要的代码上线问一个问题,if语句来检查字符串或数字,是不是在1-12之间。如何检查字符串或INT C#

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"); 

      } 
     } 
    } 

}

+0

你是什么意思“检查字符串或数字”。你只是想检查它是否是1到12之间的数字,对吗? – pushkin

+2

嗨,约瑟夫。目前这个代码甚至不会编译。就你在做什么错而言,你是否看到错误信息?你有其他尝试显示吗?我想还有一点你可以自己调试。为了给一些指点,你是不是正在阅读从控制台输入,并将其分配给什么。这需要'Console.ReadLine()'发生。将其分配给'result'。然后,看看'int.TryParse'。 –

+0

您可以尝试ISNUMBER – A3006

回答

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"); 
     } 
+0

如果包含更多OP的原始代码,那将会很棒。这将有助于OP看看如何结合使用。 – Enigmativity

+0

开发人员可以对自己添加的条件。尽管如此,他的情况也是如此 – Brijesh

+0

OP似乎没有经验。这就是我提出这个建议的原因。 – Enigmativity