2012-10-24 42 views
0

由於某種原因,這將編譯,但最終出現錯誤,我不明白爲什麼。代碼的第一部分是從正常工作的文本文件中顯示錶格,而第二部分則不正確。獲取運行時錯誤,C#將數組轉換爲Int

我不認爲它甚至到達Console.WriteLine位,這是檢查它是否做到的一種方式。任何人都能看到爲什麼

感謝您的幫助!

class Program 
{ 
    static void Main(string[] args) 

    { 
     List<float> inputList = new List<float>(); 
     TextReader tr = new StreamReader("c:/users/tom/documents/visual studio 2010/Projects/DistanceCalculator3/DistanceCalculator3/TextFile1.txt"); 
     String input = Convert.ToString(tr.ReadToEnd()); 
     String[] items = input.Split(','); 
     Console.WriteLine("Point   Latitude  Longtitude  Elevation"); 

     for (int i = 0; i < items.Length; i++) 
     { 
      if (i % 3 == 0) 
      { 
       Console.Write((i/3) + "\t\t"); 
      } 

      Console.Write(items[i]); 
      Console.Write("\t\t"); 

      if (((i - 2) % 3) == 0) 
      { 
       Console.WriteLine(); 
      } 

     } 

     Console.WriteLine(); 
     Console.WriteLine(); 

     // Ask for two bits of data which are then stored in Longtitude, Latitude and Elevation 

     Console.WriteLine("Please enter the two points that you wish to know the distance between:"); 
     string point = Console.ReadLine(); 
     string[] pointInput = point.Split(' '); 

     int pointNumber = Convert.ToInt16 (pointInput[0]); 
     int pointNumber2 = Convert.ToInt16 (pointInput[1]); 

     int Latitude = (Convert.ToInt16(items[pointNumber*3])); 
     int Longtitude = (Convert.ToInt16(items[(pointNumber*3)+1])); 
     int Elevation = (Convert.ToInt16(items[(pointNumber*3)+2])); 

     int Latitude2 = (Convert.ToInt16(items[pointNumber2 * 3])); 
     int Longtitude2 = (Convert.ToInt16(items[(pointNumber2 * 3) + 1])); 
     int Elevation2 = (Convert.ToInt16(items[(pointNumber2 * 3) + 2])); 

     Console.WriteLine("Latitude"); 
     Console.WriteLine("Latitude2"); 
+3

請包括堆棧跟蹤。對於任何問題,您在將來遇到的所有運行時錯誤也請執行此操作。也請標記相關的行號。 – Wug

+0

調試你的程序,並在必要的地方放置中斷點 –

+0

而且由於你正在做一堆'Console.Write'ing,它將有助於包含這個輸出*以及你的預期輸出以成功運行*。 –

回答

1

您正在使用十進制值,它不能轉換爲Int16。所以使用float

此外,輸出「緯度」將寫入變量的名稱,而不是它的值。 我修改你的代碼:

float Latitude = (float.Parse(items[pointNumber*3])); 
float Longtitude = (float.Parse(items[(pointNumber*3)+1])); 
float Elevation = (float.Parse(items[(pointNumber*3)+2])); 

float Latitude2 = (float.Parse(items[pointNumber2 * 3])); 
float Longtitude2 = (float.Parse(items[(pointNumber2 * 3) + 1])); 
float Elevation2 = (float.Parse(items[(pointNumber2 * 3) + 2])); 

Console.WriteLine(Latitude); 
Console.WriteLine(Latitude2); 
1

你輸入的字符串是浮動的值,而不是整數。你可以像這樣解析漂浮物:

float Latitude = (Convert.ToSingle(items[pointNumber * 3])); 
float Longtitude = (Convert.ToSingle(items[(pointNumber * 3) + 1])); 
float Elevation = (Convert.ToSingle(items[(pointNumber * 3) + 2])); 

float Latitude2 = (Convert.ToSingle(items[pointNumber2 * 3])); 
float Longtitude2 = (Convert.ToSingle(items[(pointNumber2 * 3) + 1])); 
float Elevation2 = (Convert.ToSingle(items[(pointNumber2 * 3) + 2]));