![](/img/trans.png)
[英]System.FormatException:Input string was not in a correct format
[英]ERROR : System.FormatException: Input string was not in the correct format
如果我嘗試這個:
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;
}
}
如果您的輸入字符串不包含空格,則可以調用“數組超出范圍”異常:
inputs = Console.ReadLine().Split(' ');
enemys[i] = new Enemy(inputs[0], int.Parse(inputs[1]));
您還應該檢查,如果count
大於0 ,因為它小於0 ,則嘗試創建大小錯誤的數組,
如果無法解析輸入並將count
的值設置為0, TryParse
將返回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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.