Click here to Skip to main content
15,905,414 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have this trivia game simmilar to Who wants to be a millionare on the console.

There are 8 options, A,B,C,D which represent the answers and 1,2,3,4. which represent the help options.

I identify the key pressed with this(example):

C#
string key_pressed = Console.ReadLine().ToUpper();
if (key_pressed.Equals("A"))
{
 //code here
}
else if (key_pressed.Equals("B"))
{
 //code here
}



My problem is when the user presses a diferent key from those 8. The program incresses automatically by another level(changes question). How do I fix this?

edit1.

And I have a else block limiting the statements:

C#
else
               {
                   Console.WriteLine("You need to inser a valid key.");
                   continue;
               }
Posted
Updated 27-Dec-13 6:11am
v3
Comments
bowlturner 27-Dec-13 12:11pm    
What is in your last 'else' statement? I think we need a little more code displayed.

Without seeing the rest of your code, we can't really comment on it! But...
The way I would do it is to create a method which returns a "valid key":
C#
private char GetValidKey(string validChars)
    {
    while (true)
        {
        string key = Console.ReadLine().ToUpper();
        if (key.Length > 0)
            {
            char c = key[0];
            if (validChars.Contains(c))
                {
                return c;
                }
            }
        }
    }

Then all you have to do is pass the valid date in:
C#
char c = GetValidKey("ABCD1234");
 
Share this answer
 
I added a while loop so now the code doesn't advance.

C#
string key_pressed="";
while(key_pressed=="")
{
  key_pressed = Console.ReadLine().ToUpper();
  if (key_pressed.Equals("A"))
  {
     //code here
  }
  else if (key_pressed.Equals("B"))
  {
    //code here
  }
  // else-if cases for C and D
  else
  {
    // code for the "wrong key" case. Beep, perhaps.
    key_pressed=""; // so the loop continues
  }
} // end of while loop
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900