【问题标题】:ERROR : System.FormatException: Input string was not in the correct format错误:System.FormatException:输入字符串的格式不正确
【发布时间】:2015-02-13 07:55:14
【问题描述】:

如果我试试这个:

int count = int.TryParse(Console.ReadLine(), out count) ? count : default(int);

而不是这个:int count = int.Parse(Console.ReadLine());

问题已解决,但随后出现 Array out of range 错误。 我该怎么办?

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;


class Player
{
    static void Main(String[] args)
    {
        string[] inputs;

        // game loop
        while (true)
        {
            int count = int.Parse(Console.ReadLine()); // The number of current enemy ships within range
            Console.Error.WriteLine("Count:" + count);

            Enemy[] enemys = new Enemy[count];

            for (int i = 0; i < count; i++)
            {
                inputs = Console.ReadLine().Split(' ');
                enemys[i] = new Enemy(inputs[0], int.Parse(inputs[1]));
            }

            Array.Sort(enemys, delegate(Enemy en1, Enemy en2) {
                    return en1.Dist.CompareTo(en2.Dist);
                  });

            Console.WriteLine(enemys[0].Name);
        }
    }
}


public class Enemy{
    public string Name;
    public int Dist;

    public Enemy(string name, int dist){
        this.Name = name;
        this.Dist = dist;
    }   
}

【问题讨论】:

  • 至少说一下错误发生在哪里,我想你没有得到inputs的结果你应该检查这个有2个值
  • 我的第一个问题是 int 计数的“输入字符串格式不正确”。我试图用 TryParse 方法解决。但是,它为“Console.WriteLine(enemys[0].Name);”行提供了另一个错误它是“数组索引超出范围。在播放器中”
  • 请改进您的问题和问题标题。异常究竟发生在哪里?您的代码中已经更改了什么?

标签: c# unhandled-exception unhandled


【解决方案1】:

如果您的输入字符串不包含空格,这可能会调用“数组超出范围”异常:

inputs = Console.ReadLine().Split(' ');
enemys[i] = new Enemy(inputs[0], int.Parse(inputs[1]));

您还应该检查,count 是否大于等于 0,因为如果它小于 0,则您尝试创建一个大小错误的数组,

【讨论】:

    【解决方案2】:

    TryParse 如果解析输入失败并将count 的值设置为 0 将返回 False,这意味着您随后创建了一个长度为 0 的数组,但尝试访问该数组的第一个元素不存在的

    enemys[0].Name; // This won't exist because enemy's list is empty
    

    首先你应该让用户输入一个正确的值。

    int count;
    while(!int.TryParse(Console.ReadLine(), out count)
    {
        Console.WriteLine("Not a valid value! Try Again");
    }
    

    【讨论】:

    • 我猜他需要解析Console.ReadLine().Split(' ')[1],因为这是 OP 在循环中所做的。
    • 无法隐式转换类型string' to string[]'
    • 这是一个 codingame.com 项目。我不知道这是否与他们的编译器有关,但它现在给出了 Unexpected { 错误。天啊...这是项目:codingame.com/ide/1020344fffa484480200e7a01eaf8365b1412c1 入职难题。
    • @NecatiTuran - 除了检查这个值之外,您还应该检查循环内的拆分是否包含 2 个值 (inputs.Length &gt;= 2),您可能还需要其他错误检查
    • 另外,正如@TimSchmelter 提到的(欢呼声),您还需要检查第二个拆分确实是一个有效的整数(提示:您可以再次使用尝试解析)
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2011-11-23
    • 2022-06-24
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多