Reputation: 89
i am working on Windows Forms Application. i have three buttons. i have written a method that calculates a new location for each button. but i had some errors (explained after the code). the method is:
Random random = new Random();
public int SetPointLocation()
{
int x1 = x2 - 20;
int x2;
int x3 = x2 + 20;
int y1 = y2 - 1;
int y2 = random.Next(0, 2);
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
the errors i get :
Cannot use local variable 'x2' before it is declared.
Cannot use local variable 'y2' before it is declared.
so i rearranged the method's block:
Random random = new Random();
public int SetPointLocation()
{
int x2;
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
now the errors i get:
"Use of unassigned local variable 'x2'".
The formula i've used is the way of finding the median from a Frequency tables "Statistics". but 'x2' is unknown and i want to calculate it at run-time, but because 'x2' has no value, i can't set 'x1', and 'x3'. What is the solution for this problem?!
Upvotes: 0
Views: 192
Reputation: 1653
It sounds like you really just want to pass x2 in as a parameter. You can then call the function when you do know what x2 is supose to be.
Random random = new Random();
public int SetPointLocation(int x2)
{
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
// Just return what x2 needs to be
return (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
Upvotes: 3
Reputation: 13207
Simply use
int x2 = 0;
Everything needs to be initialized before it can be used. This is a requirement of the language.
Not too close related, but hits it anyways: SO.
Upvotes: 5
Reputation: 8634
x2
is not set before using it.
Random random = new Random();
public int SetPointLocation()
{
int x2; // <- here' the problem
int x1 = x2 - 20;
...
give a value to x2
:
x2 = 123;
using a uninitialized variable is not allowed in C#.
the compiler should tell you the place where the error is.
Upvotes: 3