This question already has answers here:
C#: Use of unassigned local variable, using a foreach and if
(6 answers)
Closed 4 years ago.
I am getting an error for dateClose.closing, "use is unassigned local variable". I declared dateClose outside of the for loop and defined the value inside the for loop. How can I make that value available outside of the for loop?
public class SMA
{
public Models.DateClose SMAMethod (Queue<Models.DateClose> queue, int period)
{
decimal average, sum=0;
Models.DateClose dateClose;
for (int i = 0; i < period; i++)
{
dateClose = queue.Dequeue();
sum += dateClose.Close;
}
average = sum/period;
dateClose.Close = average; <--- error
return dateClose;
}
}
you can simply fix the error by doing
Models.DateClose dateClose = null;
however you would also want to add a null check to make sure you don't run into null ref exception if queue has no item.
You can do this. If your period variable is greater than the queue count than dateClose.Close will throw an exception.
public Models.DateClose SMAMethod (Queue<Models.DateClose> queue, int period)
{
decimal average, sum=0;
Models.DateClose dateClose = null;
for (int i = 0; i < period; i++)
{
dateClose = queue.Dequeue();
if(dateClose != null)
sum += dateClose.Close;
}
average = sum/period;
dateClose.Close = average;
return dateClose;
}
Why do you get this error:
if you have the class, member variables neednot be initialized:
public class Test
{
private int temp; // this is okay.
..
}
However, if you have a local variable, then you need to initialize them:
public void Method()
{
int variabl;
sum += variable; // error.
}
So, local variables need to be initialized but member variables neednt be.
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I can't seem to get my field / list working. I want to add to the list and use the list in CheckUserInput and PlayerMove methods. It says it's not being used but I am using it in those methods without any errors.
I tried to play around with it for a bit and all the methods are static methods so I had to make a static field.
private static List<string> AlreadyUsed = new List<string>();
private static void CheckUserInput(ref int player, ref string answer, ref bool error)
{
AlreadyUsed.Add("");
if(int.Parse(answer) > 9)
{
Console.WriteLine("You have entered a value outside the array. Skipping your turn.");
error = true;
}
else
{
for (int i = 0; i <= 9; i++)
{
if (AlreadyUsed[i] == "X" || AlreadyUsed[i] == "O")
{
Console.WriteLine("You have already entered a value in this slot. Skipping your turn.");
error = true;
}
}
}
}
private static void PlayerMove(ref string answer, string[] arr, ref int player) //make whole new class for this method?
{
for (int i = 0; i <= 8; i++) //make player move
{
if (answer == arr[i])
{
if (player == 1)
{
arr[i] = "X";
AlreadyUsed.Add(answer);
}
else
{
arr[i] = "O";
AlreadyUsed.Add(answer);
}
}
}
}
I used CheckUserInput before PlayerMove hence adding the extra value in the list. I was met with a runtime error.
Thank you!
Looks like in CheckUserInput method you iterating the list AlreadyUsed till index 9 but your code shows that the list AlreadyUsed would not have that many items to iterate and an Index out of range exception would occur.
In that for loop all you trying to check if AlreadyUsed contains strings "X" or "O", no need for the for loop you could do that with Contains method, replace your for loop in CheckUserInput method with this code:
if (AlreadyUsed.Contains("X") || AlreadyUsed.Contains("O"))
{
Console.WriteLine("You have already entered a value in this slot. Skipping your turn.");
error = true;
}
I am fairly new to programming and have run into a little problem, so sorry if its a really simple solution but im not getting it .So I'm programming a really simple version of hearthstone for practice. I created a method which generates all 5 of the cards into an array and I'm trying to use that array to make a list which will act as the players decks. However, in the for loop that I'm trying to do this in the Monsters array says it doesn't exist in the current context?
//Generates monsters and magic cards
public static MonsterCard[] GenerateCards()
{
MonsterCard[] Monsters = new MonsterCard[5];
Monsters[0].Name = "Lizard King";
Monsters[0].Attack = 4;
Monsters[0].Health = 3;
Monsters[1].Name = "Piggy";
Monsters[1].Attack = 2;
Monsters[1].Health = 1;
Monsters[2].Name = "Great Drake";
Monsters[2].Attack = 7;
Monsters[2].Health = 5;
Monsters[3].Name = "Bear";
Monsters[3].Attack = 5;
Monsters[3].Health = 3;
Monsters[4].Name = "Lion";
Monsters[4].Attack = 6;
Monsters[4].Health = 4;
return Monsters;
}
main():
int main(){
int number;
GenerateCards();
Random rnd = new Random();
//Player 1 deck
for (int i = 0; i < 10; i++)
{
number = rnd.Next(0, 4);
Player1.Deck[i] = Monsters[number]; //<-- this Monsters is where the problem comes
}
}
GenerateCard returns Monsters, but you never catch them locally in main().
Monster is local to GenerateCards() and dies right when the function finishes executing.
int main(){
// ..
MonsterCard[] Monsters = GenerateCards();
// ..
}
The above will solve that problem since you return Monsters from GenerateCards(), which has the values you are looking for inside main().
You have to move your monsters property into a global context.
That's because it is in the scope of another method, so that it's a local variable, only accessible from this method (and it only exists in this method).
An example:
void m1 ()
{
int a;
//a exists
{
int b;
//a and b exist
}
//only a exists
}
//nothing exists
void m2 ()
{
//still nothing exists
int c;
//Only c exists
}
Variables only exist in their enclosing scope. That means, if you define a variable outside of a method, it exists for all methods:
int a;
void m1 ()
{
//a exists
}
void m2 ()
{
//a still exists
}
To learn more about this, read through this.
This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 6 years ago.
I am trying to pass an integer value into a ElapsedEventHandler so I can do logic based on the integer passed in. However, when the Event is raised, the value coming in is not the value I initialized it to. I may not be understanding completely how the delegate works.
class Example
{
Dictionary<int, Timer> timer;
public Example()
{
timer = new Dictionary<int, timer>();
for(int i = 0; i < 12; ++i)
{
timer.Add(i, new Timer(5000));
timer[i].Elapsed += delegate { TimerTickCustom(i); };
}
}
public void Process() // called each cycle
{
for(int i = 0; i < 12; ++i)
{
timer[i].Start();
}
}
private void TimerTickCustom(int i)
{
// The value of i coming in does not match the dictionary key.
}
}
It depends on where the local value i is for the delegate to regard it as "specific" to it's scope. As i is defined outside the loop, the delegate doesn't define it's own "copy" of this variable - as all the delegates expect the same i.
What you need to do is assign it to a variable that's "on the same level" as the delegate itself.
Not sure if I'm using the right language here to explain it. But this should work:
class Example
{
Dictionary<int, Timer> timer;
public Example()
{
timer = new Dictionary<int, Timer>();
for(int i = 0; i < 12; ++i)
{
int iInScopeOfDelegate = i;
timer.Add(i, new Timer(5000));
timer[i].Elapsed += delegate { TimerTickCustom(iLocalToDelegate ); };
}
}
public void Process() // called each cycle
{
for(int i = 0; i < 12; ++i)
{
timer[i].Start();
}
}
private void TimerTickCustom(int i)
{
// The value of i coming in does not match the dictionary key.
}
}
There's some interesting discussion if you know which words to type into the search engine (which of course, you can't really know until someone tells you).
This question already has answers here:
Variable is assigned but its value is never used (C#)
(4 answers)
Closed 6 years ago.
I am getting an error with my code.. I am new to C# and I am trying to make a two player turn based game. Doing this using visual studio
The error is "Warning 2 The variable 'gs' is assigned but its value is never used"
The code is below;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace GridWorld
{
public class newAI : BasePlayer
{
PlayerWorldState myWorldState;
private double maxSpeed = 5f;
//public int MaxNumTurn = 15;
private int Steps;
private object count;
public newAI ()
: base()
{
this.Name = "AI FOR GAMES THE A TEAM";
// this.MaxNumTurn = 15;
var gs = new GridSquare.ContentType(); // the variable gs is now a new GridSquare content type
}
void Pathfind()
{
PlayerWorldState startingPoint = BasePlayer(GridSquare.ContentType.Snail);
int myX = 0;
int myY = 0;
if (myX == -1 || myY == -1) // if myX & myY are equal to minus 1 then increment the steps
Steps++;
{
return;
}
gs [myX, myY].Steps = 0; // outside whileloop
while (true)
{
bool madeProgress = false;
foreach (startingPoint mainPoint in gs)
{
int x = mainPoint.X;
int y = mainPoint.Y;
if (SquareOpen(x, y))
{
int passHere = GridSquare[x, y].Steps;
foreach (startingPoint movePoint in ValidMoves(x, y))
{
int myX = movePoint.X;
int myY = movePoint.Y;
int newPass = passHere + 1;
if (GridSquare[myX, myY].Steps > newPass)
{
GridSquare[myX, myY].Steps = newPass;
madeProgress = true;
}
It is not really an error. As it says, its just a warning stating that the variable 'gs' is assigned somewhere but never used anywhere. This should not cause your application to stop working.
You're declaring and defining gs in your constructor newAI and attempting to use it in Pathfind. Pathfind can't see it, because it's local to your class constructor i.e. a local scoped variable. Move it into your class like your maxSpeed, Steps and count variables.
It is only a warning, but your code is going to have undefined behaviour at the very least.
This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 8 years ago.
Hmmmm, I wonder why isn't this working...It gives an error stating "Use of unassigned local variable max". So, what is wrong with this code? I cant figure it out.
namespace ConsoleApplication1
{
class Program
{
public int CalculateHighestNum(int value1, int value2, int value3)
{
int max;
if (value1 > (value2 & value3))
{
max = value1;
}
else if(value2 > (value1 & value3))
{
max = value2;
}
else if(value3 > (value1 & value2))
{
max = value3;
}
return max;
}
static void Main(string[] args)
{
Console.Write("Enter first NUM : ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second NUM : ");
int b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter third NUM : ");
int c = Convert.ToInt32(Console.ReadLine());
Program p = new Program();
int highestnum = p.CalculateHighestNum(a, b, c);
Console.WriteLine(highestnum + " = Highest Number");
}
}
You need to set an initial value to max, or any other local variable, before you can use it.
int max = 0;
The reason for this is to reduce the chance of using a variable without assigning it a sensible default, and because the variable needs to be assigned to something before being returned. (In this case, if your if statements are all false)
The compiler will not show this error if you assign a value to the variable in all cases, such as in an else statement.
Also, as #Partha explained in the comments, you could simplify your logic to just:
return Math.Max(value1, Math.Max(value2, value3));