2017-02-24 106 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