2014-11-23 105 views
0

我嘗試將data1字符串數組轉換爲int數組結束可能還有一些其他解決方案用於此任務,但如果可能,我想使其工作。將字符串數組轉換爲int數組''System.FormatException'

問題是當我開始問題時,它得到了一個停止並給我下面的問題:mscorlib.dll中發生類型'System.FormatException'的未處理的異常「 也int.parse同樣的問題。

static int[] data() 
      { 
       StreamReader house = new StreamReader("text.txt"); 
       while (!house.EndOfStream) 
       { 
        s = house.ReadLine(); 
        Console.WriteLine(s); 
       } 
       string[] data1 = s.Split(' '); 
       int[] database = new int[(data1.Length)]; 
       for (int j = 0; j < data1.Length; j++) 
       { 
        database[j] = Convert.ToInt32(data1[j]);//Program stops here 
       } 
       return database; 
      } 

的text.txt看起來像這樣(數字用空格分隔「「):

6 1 1 
10 5 10 
20 10 20 
35 5 15 
45 5 5 
60 10 25 
75 5 10 

謝謝您的幫助!

+3

當你調試你的代碼時'data1 [j]'的值是多少?這顯然不是一個有效的整數。這個'''不會只包含你的最後一行? – 2014-11-23 14:50:20

回答

0

您可以使用Int32.TryParse。 但是,如果轉換失敗,您的數組項目超出預期。因此,最好使用一個List。而且,您僅對文件的最後一行執行轉換。 '{'位於錯誤位置。最後但並非最不重要的,您應該Disponse()流讀取器對象。

  static int[] data() 
      { 
       List<int> database = new List<int>(); 
       StreamReader house = new StreamReader("text.txt"); 
       while (!house.EndOfStream) 
       { 
        s = house.ReadLine(); 
        Console.WriteLine(s); 

        string[] data1 = s.Split(' '); 
        for (int j = 0; j < data1.Length; j++) 
        {  
         int value; 
         if (Int32.TryParse(data1[j], out value)) 
          database.Add(value)); 
        }  
       } 
       house.Dispose(); 
       return database.ToArray(); 
      } 
-2

你試過int Integer.parseInt(string)

database[j] = Integer.parseInt(data1[j]);//Program stops here 

另外,我會仔細什麼這些內容切碎了檢查字符串(例如,具有穆斯特在新行字符,是最後一行空白......),所以顯示出來的另一個環繞性格,喜歡「或[] ...

+1

'Integer.parseInt'? o.O這不是Java方法嗎? – 2014-11-23 15:00:02

+0

哎呀,我的錯誤,@SonerGönül – Heimdall 2014-11-23 16:44:06

2

大概一個空字符串進入你的分裂字符串數組

嘗試做分割時定義StringSplitOptions

string[] data1 = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); 

您還可以檢查循環中的空字符串:

for (int j = 0; j < data1.Length; j++) 
{ 
    if (string.IsNullOrWhitespace(data1[j]) 
     continue; 
    database[j] = Convert.ToInt32(data1[j]);//Program stops here 
}