简体   繁体   中英

ERROR : System.FormatException: Input string was not in the correct format

If i try this :

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

instead of this : int count = int.Parse(Console.ReadLine());

problem is solved but then it gives an Array out of range error. What should i do ?

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

This can call an "Array out of range" exception, if your input string does not contains a white space:

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

You should also check, wether count is greater equal 0 , becuase if it smaller than 0 , you try to create an array with a wrong size,

TryParse will return False if it fails to parse the input as well as setting the value of count to 0, this means you then create an array of 0 length, but try to access the first element of this array which doesn't exist

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

To start with you should make the user enter a correct value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM