为什么当我不想输入坐标时出现索引超出范围异常错误



这是我的代码:'

using System;
using System.Linq;
namespace Schiffeversenken
{
class Program
{
static void Main(string[] args)
{
// Größe der Karte
const int width = 10;
const int height = 10;
// Die Karte als 2d Array von ints initialisieren
int[,] grid = new int[width, height];
// Schiffe platzieren (fünf Schiffe der Größe 1x1)
for (int i = 0; i < 5; i++)
{
int x = new Random().Next(0, width);
int y = new Random().Next(0, height);
grid[x, y] = 1;
}
// Spiel loop
while (true)
{
// Karte anzeigen
Console.WriteLine("    0 1 2 3 4 5 6 7 8 9");
Console.WriteLine("   -------------------");
for (int yCoord = 0; yCoord < height; yCoord++)
{
Console.Write($" {yCoord} |");
for (int xCoord = 0; xCoord < width; xCoord++)
{
if (grid[xCoord, yCoord] == 0)
{
Console.Write(" ");
}
else if (grid[xCoord, yCoord] == 1)
{
Console.Write("X");
}
else if (grid[xCoord, yCoord] == 2)
{
Console.Write("O");
}
Console.Write("|");
}
Console.WriteLine();
}
Console.WriteLine("   -------------------");
Console.WriteLine("     0 1 2 3 4 5 6 7 8 9");
Console.WriteLine("    (X-Koordinate)");

// Schiessen
Console.WriteLine("Gib die Koordinaten für deinen Schuss ein (x y):");
int[] input = Console.ReadLine()
.Split(' ')
.Select(s => int.Parse(s))
.ToArray();
int x = input[0];
int y = input[1];
// Prüfen, ob die Indizes innerhalb der Grenzen des Arrays liegen
if (x >= 0 && x < width && y >= 0 && y < height)
{
// Prüfen, ob ein Schiff getroffen wurde
if (grid[x, y] == 1)
{
Console.WriteLine("Treffer!");
grid[x, y] = 2;
}
else
{
Console.WriteLine("Daneben.");
}
}
else
{
Console.WriteLine("Die Koordinaten liegen außerhalb des Spielfelds.");
}

}
}
}
}

Why do I get this IndexOutOfRangeException Error?

系统。IndexOutOfRangeException:索引超出了数组的边界。在Schiffeversenken.Program。Main(String[] args) in C:UserstimoaRiderProjectsBattleshipsBattleshipsProgram.cs:line 64

当我输入坐标时?

我已经尝试让它检查索引是否在数组的边界内。

缺少输入验证。如果用户没有以x y格式输入内容,那么访问第一部分或第二部分将导致此异常。

int x = input[0];
int y = input[1];

应该

int x,y;
do
{
string[] input = Console.ReadLine()Split(' ');
} while (!int.TryParse(input.ElementAtOrDefault(0), out x) || !int.TryParse(input.ElementAtOrDefault(1), out y))