0

My goal is to make the program print the typing of a Pokemon from user input.

My Pokemon object has members like this

    class Pokemon 
    {
        public string Name
        { get; set; }

        public string Type
        { get; set; }

        public Pokemon(string aName, string aType)
        {
            Name = aName;
            Type = aType;
        }
    }

In the main program I can create several different Pokemon. So far it's all good, but next I'd like to get a name of a Pokemon as an user input and then the program would access the Pokemon in question. Like this

Pokemon charmander = new Pokemon("Charmander", "fire");
string userInputPokemon = Console.ReadLine();

//if user input was "Charmander" the program should print "Charmander: fire"
Console.WriteLine($"{userInputPokemon.Name}: {userInputPokemon.Type}");

It is obvious to me that there's error in the last line of code. I tried googling about this and came to the conclusion that converting string to a variable name is not possible. If this indeed is impossible, how to get around this? Thank you in advance!

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • 1
    `userInputPokemon` is type `string` and `charmander` is type `Pokemon`. Does string have properties `Name` and `Type`? – Jasen Dec 07 '21 at 23:59
  • You'd want to have a collection of `Pokemon`s, and then search in the collection based on the user input. Something like: `var selected = pokemons.Where(i => i.Name.ToUpper() == userInputPokemon.ToUpper()).FirstOrDefault()`. Now, `selected` represents a Pokemon 'object' (not just the word 'charmander'). From there, you can get to the properties of the Pokemon, like: `selected.Name` and `selected.Type`. Because you are using user input strings to do the lookup, I recommend going `ToUpper()` – Jonathan Dec 08 '21 at 00:08
  • Why don't you try to create an ArrayList for all Pokemon, and then display the appropriate one after the user's entry. ArrayList poks=new ArrayList(); poks.add(new Pokemon("Charmander", "fire")); ... Or better: List poks=new... – Bokili Production Dec 08 '21 at 00:17

1 Answers1

1

Try creating a collection of the pokemon that are available, and then using the user input to look up the pokemon that matches.

var pokedex = new[] {
    new Pokemon("Charmander", "fire")
};
var pokemonByName = pokedex.ToDictionary(p => p.Name);
string userInputName = Console.ReadLine();
Pokemon matchedPokemon = pokemonByName[userInputName];

//if user input was "Charmander" the program should print "Charmander: fire"
Console.WriteLine($"{matchedPokemon.Name}: {matchedPokemon.Type}");
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • You probably want to change `Pokemon matchedPokemon = pokemonByName[userInputName];` to use `Dictionary.TryGetValue` instead. I expect that folks mis-typing Pokemon names is far from an exceptional situation – Flydog57 Dec 08 '21 at 00:55