获取运行时错误,C#将数组转换为Int

时间:2012-10-24 17:05:50

标签: c# arrays runtime-error valueconverter

由于某种原因,这将编译但最终出现错误,我无法弄清楚为什么。代码的第一部分是显示正常工作的文本文件中的表,第二部分不是。

我认为它甚至没有到达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");

2 个答案:

答案 0 :(得分:1)

您正在使用十进制值,无法将其转换为Int16。所以使用float

此外,输出“Latitude”将写入变量的名称,而不是其值。 我修改了你的代码:

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 :(得分: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]));