0

私がこれを試してみると:

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

これの代わりに :int count = int.Parse(Console.ReadLine());

問題は解決されますが、配列が範囲外のエラーになります。私は何をすべきか ?

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;
    }   
}
4

2 に答える 2

0

TryParseの値を 0 に設定するだけでなく、入力の解析に失敗した場合は False を返しますcount。つまり、長さ 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");
}
于 2015-02-13T08:04:13.600 に答える