Extremely confusing for-loop behaviour [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm encountering an extremely strange behaviour with this code fragment.
Normally the for Statement doesnt enter when counted to 16 but leaves.
In my case it enters with i=16 and executes the the Zero-Case which ends in an ArrayOutOfBoundsException.
This behavior is repeated every time I call foo()
Is there any explanation for this?
void foo()
{
Thread.Sleep(2000);
try
{
for (int i = 0; i < 16; i++)
{
#region Switch
(switch on 0 to 15 and do something unrelated)
#endregion
}
}
catch (Exception ex)
{
MessageBox.Show("Exception occured: " + ex);
}
}

Why not loop upto your array length?
for (int i = 0; i < array.Length; i++)
{
//Your secret code here
}
Also make sure you're not changing the value of i inside the loop anywhere.
You'll never get the exception with this code(unless you modify i inside the loop) irrespective of array Length.

Related

The Code Won't Execute all [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following code:
private void G1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, cost = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Cost"].Value.ToString(), out cost))
{
decimal price = quantity * cost;
G1.Rows[e.RowIndex].Cells["Total"].Value = price.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity))
{
newtotalstock = totalstock - quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
return;
}
decimal avai = 0, newavai = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai - quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
return;
} }
The problem is, it only execute 2 out of 3 the code, I mean, when the newtotalstock is calculated, the code will end.
I try to change the newavai to up above, and the result is the same, it will calculate the newavai and pass the newtotalstock. I dont know why, all the code are correct. Please help
word "return" ends function, if you are using void type method you don't really need to use return, unless you want to quit it at certain point. The code after "return" will never be executed (only exception might be during usage "yield return", but that is another story).
void someMethod()
{
doSomething();
return;
StartWorldWarThree(); //no waries, this will never be executed :)
}
Furethermore you can always make a breakpoint in your code (click on the left border of your window, or just read about it) and then check how your code is being executed :) F10/F11 to make step in your code, F5 to go to next breakpoint or end execution, if there are no more breakpoints.
Taking in count that all conditions are true the return; will stop executing the rest of the code, if you want the 3 if to be executed, remove the return; and place it the last line of the method as
void Method() {
if() {}
if() {}
if() {}
return;
}
Or dont place it at all, because that method is void and does not need it

Thread method skipping 'if' statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
When I try to use my method in created thread, thread skips 'if' statement in a loop. The problem is label4 is always shows else state. What should I do for the right operation? Here is my code;
This is where I create threads;
for(int i = 0; i <threads; i++)
{
var tempThread = new Thread(new ThreadStart(DoWork));
tempThread.Name = i.ToString();
tempThread.Start();
}
CheckForIllegalCrossThreadCalls = false;
And this is what my thread method do;
public void DoWork()
{
for(int i=2; i < variable/ 2; i++)
{
if (variable% i == 0) label4.Text ="yes not";
else label4.Text = "yes";
}
}
I'm guessing this is what you want to do, but since you haven't told us your goals we can only guess
public void DoWork()
{
for(int i=2; i < variable/ 2; i++)
{
if (variable% i == 0) {
label4.Text ="yes not";
return;
}
}
label4.Text = "yes";
}
I don't use C# but if DoWork is how you create a Thread then I think it's a bit much for something that should take almost no time at all to finish.

Function won't return any value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a problem that I think might be really easy to solve but since I'm a C# noob I can't understand what I'm doing wrong. I have two functions: addValues() and showMessage(). My problem is in addValues(). I have two MessageBox that show exactly what they're supposed to show, but in the showMessage() function the values are not being received, it always tells me that the day and dias.Count are 0. What am I doing wrong? Thank you!
On Form1:
public List<Despesas> dias = new List<Despesas>();
public struct Despesas
{
public double transportes;
public double alimentacao;
public double vestuario;
public double agua;
public double luz;
public double educacao;
}
On Class Management:
class management : Form1
{
int day=0;
public double addValues(double transportes, double alimentacao)
{
Despesas dia = new Despesas();
try
{
dia.transportes = transportes;
dia.agua = agua;
dias.Add(dia);
}
catch
{
MessageBox.Show("Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Count " + dias.Count);
day++;
MessageBox.Show("" + day);
return day;
}
public void showMessage()
{
MessageBox.Show("Day " + day);
MessageBox.Show("Count: " " + dias.Count);
for (int i = 0; i < day; i++)
{
MessageBox.Show("Agua: " + dias[i].agua + "\nTransportes: " + dias[i].transportes);
}
}
In the comments, you mention that you actually have two instances of the management class.
Changes to one instance of an object do not propagate to other instances of that object (unless it was modified on a static member, but thats a bit different).
This holds true even if you modify a base class member, as your code does. This is because instantiation of a derived class also instantiates a new base class object.
The solution is to just use one management object instance, and pass it around as needed. You do this just like any other type:
public void Foo(management myClass)
{
...
}
A few other notes:
management is not a very good name for a class, as its not very descriptive. Also, class names in C# should be PascalCase, so it should be Management
Inheritance is probably not the right relationship between management and Form1. Is management really a "type of" or "is a" Form1?

Thread name not displaying in Thread.currentThread.Name [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In the code below, in the second Console.WriteLine command, it fails to print the thread name. Can someone tell me why?
public class Retailer
{
public void retailerFunc()
{
ChickenFarm chicken = new ChickenFarm();
for (Int32 i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Int32 p = chicken.getPrice();
Console.WriteLine("Store{0} has everyday low price: ${1} each", Thread.CurrentThread.Name, p); // Thread.CurrentThread.Name prints thread name
}
}
public void chickenOnSale(Int32 p)
{
// order chickens from chicken farm – send order into queue
Console.WriteLine("Store{0} chickens are on sale: as low as ${1} each", Thread.CurrentThread.Name, p); // Thread.CurrentThread.Name cannot print a name
}
}
Has your application set the thread name? The default value of Thread.Name is null. I'm guessing at the point chickenOnSale is called, the current thread does not have a name.
And for future reference, MSDN does have an article on how to set a thread name. You can only set it once; any subsequent attempts to set the Thread.Name property result in an InvalidOperationException.

Can't stop a timer in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want the timer to stop when the ImageNumber is equal to zero.
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
if (ImageNumber1 < 20)
{
ImageNumber1++
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
}
If I add a return statement after the first if statement the second if statement is disabled.
I want the timer to stop when the ImageNumber is equal to zero.
You appear to already know how to do this, assuming Health_Regen is a Timer then:
Health_Regen.Enabled = false;
Will disable your Timer.
If I add a return statement after the first if statement the second if statement is disabled.
That is to be expected as you are using the return keyword which will prevent anything after it within the same code block from being executed.
Your question does not make exactly what you are asking clear, however, I am assuming from your comment that the second if statement is not executed that you want to update the HealthBar.Image value even if the Timer is disabled? If so then something like below should work for you
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
{
Health_Regen.Enabled = false;
}
else if (ImageNumber1 <= 20)
{
ImageNumber1 += 1;
}
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png";
}
You should just be able to call the Stop method on the timer instance.
if (ImageNumber == 0)
{
Health_Regen.Stop();
}
This is just a guess!.
Replace
if (ImageNumber1 == 0)
with
if (ImageNumber1 >= 20)
Your timer will already stop when ImageNumber1 equals 0, but it just never counts down to 0.
Also if you change ImageNumber1 to 0. It may already be running the timer which will increment it by one and skip the stopper, so pretty much the way you have it coded it's based on luck right now.
The luck happens if you change ImageNumber1 while timer is already running.
Try this:
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
else if (ImageNumber1 < 20)
{
ImageNumber1++;
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
Still the luck may still happen best you can do is stop the timer outside the timer when you make it ImageNumber1 = 0;
Best Fix:
Also a better solution is to fix your program to start at ImageNumber1 = 20 and just keep going down to 0.. when it hits 0 stop the timer.. you shouldn't make it this confusing all you will have to do is rename a few png files in a new order! instead of
1.png now it will be 20.png
2.png now it will be 19.png
and so on and so on..

Categories

Resources