Reputation: 11
Welcome, I've a problem with small funcion in switch. My problem is "Use of unassigned local variable 'matrix'" Here is a code:
static void Main(string[] args)
{
char wyj = 'n';
do
{
Console.WriteLine("1. add numbers into matrix \n2. show matrix \n3. end");
int a;
Console.Write("\nYour choice: ");
a = int.Parse(Console.ReadLine());
switch (a)
{
case 1:
Console.WriteLine("You choose: 1");
int element;
Console.Write("\nsize of matrix: ");
int matrixsize;
matrixsize = Int32.Parse(Console.ReadLine());
int[,] matrix = new int[matrixsize, matrixsize];
for (int i = 0; i <= matrixsize - 1; i++)
{
for (int j = 0; j <= matrixsize - 1; j++)
{
Console.Write("element{0},{1} =", i + 1, j + 1);
element = int.Parse(Console.ReadLine());
matrix[i, j] = element;
}
}
break;
case 2:
Console.WriteLine("You choose 2");
foreach (int x in matrix)
Console.Write(x);
break;
case 3:
Console.WriteLine("End the program? y- yes, n- no");
wyj = char.Parse(Console.ReadLine());
break;
}
}
while (wyj != 'y');
Console.WriteLine("Koniec programu!");
Console.ReadKey();
}
What i need to do?
After Doc Brown answer, in case 2 nothing happens, the matrix is empty. I think the loop is the problem?
Upvotes: 0
Views: 171
Reputation: 76246
The matrix
variable is local to the switch. The case 2
uses the variable from case 1
, because case
does not introduce a scope, but it is never initialized there, because the initializer is not executed when doing case 2
.
Moving the variable out of the switch
will silence the error if you provide initializer, but it will still be a new variable in each iteration, so when you fill it in in case 1
, it will come out empty when doing case 2
in next iteration. You need to move the variable all the way out of the loop to have to values persist.
You still should not assume that user provides the inputs in correct order, so in the case 2
you have to check that the matrix was already filled in.
Upvotes: 0
Reputation: 20044
You should not assume that the user first enters 1, then 2, but expect that this might happen the other way round.
int[,] matrix
must be done before the switch statement, and you should set the variable to null there int[,] matrix=null;
matrix = new int[matrixsize, matrixsize]
can stay where it is, butcase 2
block, you have to check if matrix was initialized if(matrix!=null) {/*...*/}
Upvotes: 2
Reputation: 677
You've made an assumption that the compiler can't verify--that you will always generate the matrix be forming viewing it. The compiler knows that this doesn't have to be the case in a switch statement, so it prevents you from using a variable which may never have been set (or in this case, even declared). If you want to keep this code, declare the variable outside of the case and initialize it to a new matrix. Then check in case two if it is safe to display.
Upvotes: 0