# Problem with the enums

3
``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ejercicio_2
{
class Program
{
enum direcion { arriba=1,abajo=3,derecha=2,izquieda=4};
static void Main(string[] args)
{
string num = "";
Console.WriteLine("Escribe la direcion que desees tomar");
for (int i = 0; i < num.Length; i++)
{
Console.WriteLine("{0}", num.Substring(i, 1));
}
}
}
}
``````

Hello my problem is the following, the statement of the exercise says that we have a drone that can go up down right left. That we associate an entire value to each enum. Enter the numbers (1,2,3,4) on the keyboard and show us on the top right below. The problem is that I put up in the initialization of the enums a number for example above = 1 and then if I enter by keyboard 1 does not come up, it shows me 1. I do not know how I can do it. I had thought about saving what you put in a chain like in the example and then buying character by character and if it is a 1 that shows up, if it is 2 that shows right, etc. But I do not know how to compare the characters of the chains. But the question would be using the enums, because the exercise tries to practice with them.

asked by winnie 16.10.2018 в 10:44
source

4

What you have to do is find the value within `enum` by your index:

``````class Program
{
enum direccion { arriba=1, abajo=3, derecha=2, izquieda=4 };
static void Main(string[] args)
{
string num = "";
Console.WriteLine("Escribe la dirección que desees tomar");
direccion d = (direccion)Int32.Parse(num);

Console.WriteLine(d);
}
}
``````

Edit:

First we receive the `string` that the user enters, here instead of doing the `substring` you can do a `split` by commas, I think it will be easier:

``````var numeros = str.Split(',');
``````

In this way you transform your `string` entered in a `array` . Now you just have to loop through this `array` :

``````foreach (var numero in numeros)
{
direccion d = (direccion)Int32.Parse(numero);

Console.WriteLine(d);
}
``````

Here you have to understand a bit how `enums` works.

Simplifying: is an array of key = value , that is, when you have created the `enum` you have set the values "above", "below "," etc " and you have assigned them an index 1, 3, etc .

To derive a value from this array there are several ways:

• By value:

``````Console.WriteLine(direccion.arriba)  // Esto nos devolverá "arriba"
``````
• By index:

``````Console.WriteLine((direccion)1)  // Esto nos devolverá "arriba"
``````
• We can also find which index has a value:

``````Console.WriteLine((int)direccion.arriba); // Esto nos devolverá 1
``````