8
The idea is to create an integer array with the amount of user-defined rows and columns. Then an existing value in the matrix must be informed and the program must return the values immediately to the left, right, above and below the matrix.
Example
Número de Linhas: 3 Número de Colunas: 4 10 7 15 12 21 11 23 8 14 5 13 19 Número que deseja verificar: 11 Esquerda: 21 Direita: 23 Acima: 7 Abaixo: 5
The code I developed works perfectly when entering a matrix value that is not in the 'corner'. If I enter a value that is in the 'corner' the program throws the exception System.IndexOutOfRangeException
indicating that there are no values immediately above/left/below/right of the desired value.
How could I treat this exception? Any tips are welcome since my goal is to learn. Follow my code for analysis.
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string[] Linha = Console.ReadLine().Split(' ');
int[,] Numeros = new int[int.Parse(Linha[0]), int.Parse(Linha[1])];
for (int i = 0; i < int.Parse(Linha[0]); i++)
{
string[] vet = Console.ReadLine().Split(' ');
for (int j = 0; j < int.Parse(Linha[1]); j++)
{
Numeros[i, j] = int.Parse(vet[j]);
}
}
string[] Localizacao = new string[4];
int Num = int.Parse(Console.ReadLine());
for (int i = 0; i < int.Parse(Linha[0]); i++)
{
for (int j = 0; j < int.Parse(Linha[1]); j++)
{
if (Numeros[i, j] == Num)
{
Localizacao[0] = Numeros[i, j - 1].ToString();
Localizacao[1] = Numeros[i, j + 1].ToString();
Localizacao[2] = Numeros[i - 1, j].ToString();
Localizacao[3] = Numeros[i + 1, j].ToString();
}
}
}
Console.WriteLine("Esquerda: " + Localizacao[0]);
Console.WriteLine("Direita: " + Localizacao[1]);
Console.WriteLine("Acima: " + Localizacao[2]);
Console.WriteLine("Abaixo: " + Localizacao[3]);
Console.ReadLine();
}
}
}
This exception usually occurs when an instruction attempts to access an element at an index greater than the maximum allowed index.
– Vinícius
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero