Reputation: 155
I'm building a c# hangman game and I'm looking to access some information from on of the if statements unto another. I'm totally new to programming so I'm sorry if this is a stupid way of doing it, if there is a better one I would really appreciate input.
Anyway, here's the code:
if (menyalternativ == "1")
{
//Här får spelare lägga till fem egna ord utöver det hårdkodade ordet "projektarbete"
Console.WriteLine("\n\tLägg till 5 ord");
Random rng = new Random();
string[] ordlista = new string[5];
ordlista[0] = Console.ReadLine();
ordlista[1] = Console.ReadLine();
ordlista[2] = Console.ReadLine();
ordlista[3] = Console.ReadLine();
ordlista[4] = Console.ReadLine();
int index = rng.Next(5);
I would like to take the ordlista[index] data to use in a later statement:
else if (menyalternativ == "3")
{
string hemligtord = "projektarbete"; //This I would like to be the random word from earlier.
char[] gissatord = new char[hemligtord.Length];
char gissa;
bool rättord = false;
Kontroll kontroll = new Kontroll();
for (int i = 0; i < gissatord.Length; i++)
{
gissatord[i] = '-';
}
Any and all help is greatly appreciated!
Upvotes: 0
Views: 89
Reputation: 726709
The ordlista
array is local to the block where it is declared (i.e. the statements within the same curly braces {...}
, after the point of declaration).
If you need to use it in another block of code, you must declare it in the scope where it is visible to both code blocks. However, in this case you may have a logical error, because the else if
will never be entered after the if
block has been processed, unless the entire chain of if
-else if
s is enclosed in a loop.
If you do have a loop outside the if
statements, and you would like to use ordlista
to pass the data between iterations, you need to declare the variable outside of the loop. Otherwise, it is going to be re-initialized in each iteration, defeating the purpose of having it in the first place.
Upvotes: 1