0

Well, i've been having a problem with the code of a memory game. It is like a simon says but with numbers in C#.

The problem comes when, in the code, i use the Console Readkey to let the player make an input. But, the problem comes when i convert to int a number... It takes it like i had put a value that mismatched the type of data. Why does that happen=

     public void playersTurn() {
        for (int i = 0; i < 6; i++) {
            if (!(failure)){
                playerInput = Console.ReadKey().Key.ToString(); // if i put, for example, 5
                Console.Write(playerInput); // it throws 5D50 (this was just to see if something weird was happening)
                try{
                    playerNumber = Convert.ToInt32(playerInput);
                }
                catch(FormatException e){
                    Console.Clear();
                    Console.WriteLine("Solo numeros, chico"); // there is always an exception
                }
                Console.Write(playerNumber + " ");
                if (playerNumber != thoseNumbers[i]) {
                    Console.WriteLine(" ");
                    Console.WriteLine("¡ERROR!");
                    failure = true;
                }
            }
            thoseNumbers[i] = 0;
        }
  • try using `int.TryParse` instead. – M. Adeel Khalid Mar 24 '17 at 07:00
  • The exception is reasonably clear. Look at the string. Does it look like a number? No? Then you need to fix that. In this case, you probably should use `ReadKey().KeyChar` instead (you seem to want to respond to a single key input instead of making the user press return). You can subtract `'0'` from the `KeyChar` value to get the actual digit value (i.e. `playerNumber = Console.ReadKey().KeyChar - '0';`) – Peter Duniho Mar 24 '17 at 07:39

1 Answers1

0

The convert method throws exception because it expects a number. If you pass it a string like 5D50 it will not know what to do with 'D' so it will throw exception.

Readkey() returns code of key, not the value the key is used for. Try this:

Convert.ToInt32(Console.Readline());