2013-08-21 45 views
1
using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Int32 a = 3; 
      Int32 b = 5; 

      a = Console.Read(); 

      b = Convert.ToInt32(Console.ReadLine()); 

      Int32 a_plus_b = a + b; 
      Console.WriteLine("a + b =" + a_plus_b.ToString()); 
     } 
    } 
} 

我得到的ReadLine()功能的錯誤消息:Console.Read()和到Console.ReadLine()出現FormatException

出現FormatException了未處理。

什麼問題?

+2

也許你是把該字符串不是有效的整數?嘗試讀取數據到變量,並添加一些驗證使用'TryParse' – wudzik

+0

在哪個特定的行給出這個錯誤,這個變量的值是什麼.. –

+0

如果我評論「a = ...」或「b = .. 。「然後一切都很好。 這些值只是簡單的數字,如4或7. – BlackCat

回答

3

我想這只是因爲你按輸入第一個號碼後,按ENTER鍵。 讓我們分析你的代碼。您的代碼讀取您輸入的a變量Read()函數所輸入的第一個符號。但是,當你按回車鍵ReadLine()函數返回空字符串,它是不正確的格式將其轉換爲整數。

我建議你用ReadLine()函數來讀取這兩個變量。所以輸入應該是7->[enter]->5->[enter]。那麼你就得到a + b = 12

static void Main(string[] args) 
{ 
    Int32 a = 3; 
    Int32 b = 5; 

    a = Convert.ToInt32(Console.ReadLine()); 
    b = Convert.ToInt32(Console.ReadLine()); 

    Int32 a_plus_b = a + b; 
    Console.WriteLine("a + b =" + a_plus_b.ToString()); 
} 
+0

是的, iput1:5 [enter] - >我得到了一個異常 input2:56 [enter] --->一切都很好 – BlackCat

+0

我應該怎麼做,以避免這種情況? – BlackCat

+0

@BlackCat我編輯了我的答案 – Reniuz

1

我認爲你需要把:

b = Convert.ToInt32(Console.ReadLine());

裏面一個try-catch塊。

祝你好運。

1
namespace ConsoleApplication1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     Int32 a = Convert.ToInt32(Console.ReadLine()); 
     Int32 b = Convert.ToInt32(Console.ReadLine()); 

     Console.WriteLine("a + b = {0}", a + b); 
    } 
} 

}

+0

ReadLine()的返回值是字符串。您必須將其轉換爲Int32 – BlackCat

+0

更改「Int32 b = 5;」成字符串b =「5」; – N8tiv

+0

「a」也被聲明爲Int32,您需要將Convert.ToInt32添加到您的Console.Read方法以及... – N8tiv

1

你想要做的就是使用嘗試捕捉,因此,如果有人提出的一些錯誤,你可以找到

using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Int32 a = 3; 
      Int32 b = 5; 

      a = Console.Read(); 
      try 
      { 
       b = Convert.ToInt32(Console.ReadLine()); 
       Int32 a_plus_b = a + b; 
       Console.WriteLine("a + b =" + a_plus_b.ToString()); 
      } 
      catch (FormatException e) 
      { 
       // Error handling, becuase the input couldn't be parsed to a integer. 
      } 


     } 
    } 
} 
+0

我試過這個。 輸入:5 當我點擊輸入按鈕後,程序變爲完成,因爲它在try塊中有異常。 – BlackCat

+0

我更喜歡tryParse而不是tryCatch塊 – jomsk1e

+0

是Blackcat,就是try的目的,除了。因爲你可以繼續執行正常的代碼,你必須做一些錯誤處理。如果這是一個小錯誤,你想繼續,你應該使用tryParse,因爲JRC說。因此,例如,如果我寫入「q」,並且您只想將值替換爲0,則可以嘗試tryParse,如果失敗,則將該值設置爲0。 – Smarties89

0

你可以試試這個:

Int32 a = 3; 
Int32 b = 5; 

if (int.TryParse(Console.ReadLine(), out a)) 
{ 
    if (int.TryParse(Console.ReadLine(), out b)) 
    { 
     Int32 a_plus_b = a + b; 
     Console.WriteLine("a + b =" + a_plus_b.ToString()); 
    } 
    else 
    { 
     //error parsing second input 
    } 
} 
else 
{ 
    //error parsing first input 
}  
相關問題