我在将整数转换为字符串时遇到问题

时间:2021-02-13 20:52:36

标签: c# integer

****n

我想要做的是转换 namespace C2360_Ch07_Console1_InRange { class InRange { static void Main(string[] args) { Console.WriteLine("Num:"); String theLine; theLine = Console.ReadLine(); try { theLine = Convert.ToInt32(Console.ReadLine());//cant convert } catch (FormatException) { Console.WriteLine("Input string was not in a correct format."); } IsWithinRange(theLine); } static void IsWithinRange(String theLine) { int Line1; Int32.TryParse(Console.ReadLine(), out Line1); try { if ((Line1 < 1) || (Line1 > 10)) { throw new OverflowException(); } } catch (OverflowException) { Console.WriteLine("number must be between 1 and 10."); } Console.ReadLine(); } } } stringeger 以验证 intMain 方法。当我将 IsWithinRange 转换为 theLine 时,我收到一个错误,即评论所在的位置。这有可能吗? 有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

我建议提取一个方法来读取整数值:

   private static int ReadInteger(string title) {
       while (true) {
           Console.WriteLine(title);

           if (int.TryParse(Console.ReadLine(), out int result))
               return result;

           Console.WriteLine("Incorrect syntax. Please, try again");
       }
   }    

然后使用它:

   static void Main(string[] args) {
       int theLine = 0;

       while (true) { 
         theLine = ReadInteger("Num:");

         // theLine is an integer, but we want an extra conditions meet:  
         if (theLine >= 1 && theLine <= 10)
           break;

         Console.WriteLine("The value must be in [1..10] range. Please, try again"); 
       }

       // from now on theLine is an integer in [1..10] range 
       //TODO: put relevant code here
   }

请注意,exceptions FormatException, OverflowException 是针对异常行为;在这里(用户输入验证),好的旧 if 就足够了。

编辑:如果你不想提取方法(为什么?)但保留 IsWithinRange 你可以这样写:

   static void Main(string[] args) {
       int theLine = 0;

       while (true) {
           Console.WriteLine("Num:");

           if (!int.TryParse(Console.ReadLine(), out theLine)) {
               Console.WriteLine("Syntax error. Please, try again");

               continue;
           } 

           if (IsWithinRange(theLine))
               break;

           Console.WriteLine("Sorry, the value is out of range. Please, try again"); 
       }
       // from now on theLine is an integer in [1..10] range 
       //TODO: put relevant code here

IsWithinRange 可以在哪里

   // Least Confusion Principle: For "Is [the value] Within Range" question
   // the expected answer is either true or false
   private static bool IsWithinRange(int value) {
       return value >= 1 && value <= 10;
   }
相关问题