Radu Harabagiu Radu Harabagiu - 2 months ago 5
C# Question

Name doesn't exist in the current context error happening in the same class

I'm making a simple rock paper scissors game that uses keyboard input. I've realised that it's a better thing to type 1 for rock 2 for scissors etc than to write rock paper or scissors, but I want the console to write at the end what each player chose(rock, paper or scissors) instead of 1,2,3.

So when the string that has the number gets correct user input, another string
becomes rock paper or scissors.However, although I'm only using one class and initialising

RealChoice1
and
RealChoice2
at the beginning of the while, I get the "name doesn't exist in the current context" error for both of them

while (true)
{
string RealChoice2;
string RealChoice1;

while (true)
{
var key1 = System.Console.ReadKey(true);

if (key1.Key == ConsoleKey.Enter)
break;

Choice1 += key1.KeyChar;
}


if (Choice1 == "exit")
return (int)ExitCode.UserInputExit;
else if (Choice1 != "1" && Choice1 != "2" && Choice1 != "3")
{
Choice1 = null;
Console.WriteLine("");
Console.WriteLine("Please write 1, 2 or 3");
}
else if (Choice1 == "1" || Choice1 == "2" || Choice1 == "3")
{
switch (Convert.ToInt32(Choice1))
{
case 1:
RealChoice1 = "Rock";
break;

case 2:
RealChoice1 = "Scissors";
break;

case 3:
RealChoice1 = "Paper";
break;
}
break;
}
} //End of player 1 input


string Choice2 = null;
Console.WriteLine("");
Console.WriteLine("Player2, please type what you choose");
//Player2Input:

while (true)
{
while (true)
{
var key2 = System.Console.ReadKey(true);
if (key2.Key == ConsoleKey.Enter)
break;

Choice2 += key2.KeyChar;
}

if (Choice2 == "exit")
return (int)ExitCode.UserInputExit;
else if (Choice2 != "1" && Choice2 != "2" && Choice2 != "3")
{
Choice2 = null;
Console.WriteLine("");
Console.WriteLine("Please write 1, 2 or 3");
}
else if (Choice2 == "1" || Choice2 == "2" || Choice2 == "3")
{
switch (Convert.ToInt32(Choice2))
{
case 1:
RealChoice2 = "Rock";
break;

case 2:
RealChoice2 = "Scissors";
break;

case 3:
RealChoice2 = "Paper";
break;
}
break;
}
}

Answer

You need to declare your variables outside of the while loop if you want them to be available everywhere in the scope of your code. Currently, since you're declaring them within the first while loop, they wouldn't be available where you're using them inside the second while loop.