Bugs in Visual Studio 2010/Weird For-Loop behaviour? - c#

I was just shocked when my application fired an IndexOutOfRanage exception now. I opened the Debugger Locals Pane and discovered that my integer crossed it's boundary? Basically I have something like this in my code:
string folder = Extender.GetSetting<string>("textFolder");
string mlink = folder + "\\" + filename + ".txt";
if(File.Exists(mlink))
{
string fContent = File.ReadAllText(mlink);
rtbLearnGuide.Text = fContent;
string[] strings = fContent.Split(' ');
for (int i = 0; i < strings.Length; i++, words.Enqueue(strings[i]));
}
The problem here is that i reaches the length of strings[], I have attached a picture below.
What's even more weird is that I failed to reproduce this behavior a second time.
NB: I experienced something similar earlier today with this.CreateGraphics(); My code was something like:
var dc = this.CreateGraphics();//and some other stuff
The result was that it failed to draw it even after trying to rerun like 4 times, then I went back to the code and defined dc explicitly, voila it was working. Then I changed it back to var, it was still working :/?
What might be wrong?
EDIT:
I just discovered that changing the order works. For instance:
for (int i = 0; i < strings.Length; words.Enqueue(strings[i]), i++);
doesn't fire any errors.

To answer the first part of your question, you are executing the Enqueue before the for loop's test condition. So
for (int i = 0; i < strings.Length; i++, words.Enqueue(strings[i]));
should be:
for (int i = 0; i < strings.Length; i++) words.Enqueue(strings[i]);
Basically, the "increment" portion will always execute before the "test" portion.

Format your for loop logically and you will not have that error.
for (int i = 0; i < strings.Length; i++)
words.Enqueue(strings[i]);
In your code, "i" is incremented past the condition (strings.Length) you are THEN running the word.Enqueue on an out of bounds "i".
Your loop (in pseudo code):
i = 0
Loop_Label:
IF i >= strings.Length THEN GoTo End_Label
... where the for loop body should go ...
i = i + 1
words.Enqueue strings[i]
GoTo Loop_Label
End_Label:

Related

how do i count the words in a string list

I am constantly running into an overload problem,
I have looked it up but nothing seems to look like my scenario...
I was hoping that the people here could help me.
An example of my code looks as followed.
string s = textbox.text;
char[] delimiter = {' '};
string[] word = s.split(delimiter); //this gets a set of words from s.split
for (int i = 0; i <= word.length; i++) //I also tried word.count()
{
int ii = 0;
int counter = wordlist.count;
bool test1 = false;
while (test1 == false || ii != counter +1)
{
if (word[i] == wordlist[ii]) //this is where it gets stuck. It wants to load more word[i] than what there are in the list...
{
//function gets preformed
test1 = true;
}
else
{
ii++;
}
}
}
please help me, this part of my script is vital...
thank you for your time!
Shouldn't it be string[] words = s.Split(' ');
Even if we say your word is s.Split(' '); then it should be string[] words = word not string[]=word
And to count how much words are in that array just do int howManyWords = words.Length;
Also if you want to go through loop as many times as there are words in list you should do:
for(int i = 0; i < words.Lenght; i++)
{
//Do your stuff
}
While your question is very unclear (you should post what error you are getting at the least it would have made answering much easier) you cleared it up in the comments. What you are getting is an index out of range exception.
You need to change your loop
for (int i = 0; i <= word.length; i++)
To
for (int i = 0; i < word.length; i++) // preferable
or
for (int i = 0; i <= word.length - 1; i++) // not preferable
Arrays are index at 0 not 1. The length property will give you the total number of elements in the array. When you get to your last index the value of i will be greater than the number of elements because you started counting at 0.
You also need to change your while loop because you have an out of range exception happening there. Its the same problem except this time you added one to make it even worse.
while (test1 == false && ii != counter - 1)
Change it to a minus so it never goes out of range. Also change the logic to an && instead of || with the or when it finds a match it will never increment the ii so it will be stuck forever in the while.
You would also want to break out of the loop once you find the match.
Ok, so I found my problem. it was because there were no words in wordlist[] for it to read... my bad!
I should just place in a prevention method next time...
But thank you guys for your assistance! the code is now working as should!

How can i make the FOR to loop backward ? Getting some errors

for (int i = uids.Count; i > 0; i--)
{
counting += 1;
if (counting == 30)
break;
string currentUidOnServer = uids[i - 1];
if (!seenUids.Contains(currentUidOnServer))
{
OpenPop.Mime.Message unseenMessage = client.GetMessage(i + 1);
newMessages.Add(unseenMessage);
seenUids.Add(currentUidOnServer);
allMessages.Add(unseenMessage);
int nProgress = (uids.Count - i + 1) * 100 / uids.Count;
backgroundWorker1.ReportProgress(nProgress, client.GetMessageCount().ToString() + "/" + i);
}
}
The variable uids contain 7038 items.
I want to report to the backgroundworker progresschanged event.
And it does reporting but it did backward started from 7038 and 100%
And i want it to report from 0% to 100% so i changed the FOR to
for (int i = uids.Count; i > 0; i--)
It was
for (int i = 0; i < uids.Count; i++)
The first error out of index exception was on the line
string currentUidOnServer = uids[i - 1];
So i changed it to [i - 1]
Now i'm getting exception on the line
OpenPop.Mime.Message unseenMessage = client.GetMessage(i + 1);
Since 7038 + 1 not exist.
So i messed it all.
How this two lines i have/had the exceptions should be ?
This is the typical way to do this:
for (int i = uids.Count - 1; i >= 0; i--)
Then, use uids[i] and maybe client.GetMessage(i), however I have no idea, what "client" is in your code
Arrays in C# (and all the other C-like languages) are zero-indexed, which means that the first item in the array is at position 0. Attempting to access an array index that is less than 0 or greater than or equal to the number of elements in the array will result in an error as you have seen.
The first form of your loop:
for (int i = uids.Count; i > 0; i--)
...produces a sequence of numbers (on your 7038-item array) from 7038 down to 1. Since 7038 is an invalid array index (1 past the end of the array) and the sequence doesn't include 0, the array access expressions in the loop all use i -1 to shift the entire sequence down by 1.
To properly reverse the for without changing any other code you need to produce a sequence from 1 up to 7038, like this:
for (int i = 1; i <= uids.Count; i++)
This is the direct opposite form of your original.
Personally I would prefer that the loop variable be the array index most of the time, and my first instinct when I see a > 0 condition in a for statement is that someone forgot to put the = in.
You could just reverse your array with Array.reverse() and then iterate over it using i++ as per your original approach
Oops I thought this was JavaScript question lol, o well the approach I said can conceptually be applied to any language, just need to find the array reverse for your language
If I understood correctly, originally i went from 0 to uids.Count - 1. If you can get back to that situation, then your formula for nProgress should be
int nProgress = (i + 1) * 100 / uids.Count;

C# When using foreach on a list of arrays, the foreach only iterates 5 times even though the list has length 86

I'm writing a chess engine in C#, and I'm trying to debug move generation. I've been using breakpoints so far to check variables, but I need a better way to debug. Despite the fact that a breakpoint shows that this list has a length of 86, the loop only runs 5 times. The only thing I can think of is that the arrays in the list have a length of 5, but I have no idea what would be causing this.
foreach (int[] debugBoard in futures)
{
for (int i = 0; i < 5; i++)
{
Debug.Write(debugBoard[i].ToString().PadLeft(3, ' '));
}
Debug.Write("\n");
int[,] debugOutBoard = new int[8, 8];
Array.Copy(chessBoard.Pieces(), debugOutBoard, 64);
if (debugBoard[0] < 0 || debugBoard[1] < 0 || debugBoard[2] < 0 || debugBoard[3] < 0 || debugBoard[0] > 7 || debugBoard[1] > 7 || debugBoard[2] > 7 || debugBoard[3] > 7)
break;
debugOutBoard[debugBoard[2], debugBoard[3]] = debugOutBoard[debugBoard[0], debugBoard[1]];
debugOutBoard[debugBoard[0], debugBoard[1]] = 0;
int rowLength = debugOutBoard.GetLength(0);
int colLength = debugOutBoard.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Debug.Write(debugOutBoard[i, j].ToString().PadLeft(3, ' '));
}
Debug.Write(Environment.NewLine + Environment.NewLine);
}
}
Also, I tried using a concurrentbag to store moves in (I was going to multithread the move processing later on) but as soon as the foreach loop touched the concurrent bag, all the memory values of the bag changed to one value. I've been stuck on this roadblock for days, and I really need help.
Your if statement breaks out of the for loop when its condition is met, I presume this happens for the first time on the 5th/6th iteration.
What I meant to do is iterate to the next element. What command would I use to do that? –
You need to use continue instead of break
If 'futures' contains 86 items the only way it could stop iterating is if an exception occurs. Visual studio (In default settings) should break when this occurs unless you handle the exception somewhere.
Wrap the whole thing in a try{} catch{} and set a breakpoint in catch and see if it hits.

Loop stops all code after one iteration

I have a loop which in theory should loop 40000 times but exits and doesn't continue with code after the loop, just after one iteration. I figured that I wasnt being a silly willy about the for-loops since it didn't continue after the loops at all, so that might be something with restrictions for Lists? Or mayby something about the VS-debugger that isn't working preperly? (probably not tho...)
Edit: Thanks for pointing out that the last layer was pointless. I edited the code, but the problem persists.
Edit2: To clarify, the code does not result in an exception, or breaks. It just stops without any notifications, and shows the form(since I do a windows forms application). Just... it just don't want to continue and skips the rest of the code.
for (int i = 0; i < hiddenLayerDepth - 1; i++)
{
Connectors.Add(new List<List<List<List<Connector>>>>());
for (int j = 0; j < playfieldSize; j++)
{
Connectors[i].Add(new List<List<List<Connector>>>());
for (int k = 0; k < playfieldSize; k++)
{
Connectors[i][j].Add(new List<List<Connector>>());
for (int l = 0; l < playfieldSize; l++)
{
Connectors[i][j][k][l].Add(new Connector());
}
}
}
}
hiddenLayerDepth is set to 5 when entering the loop, and playfieldSize is set to 10. It enters the innermost loop and executes the code inside, then it just stops without increasing m.
Missing
Connectors[i][j][k].Add(new List<List<Connector>>());
If you know the sizes you should just create and array up front
Well, I tried to add a 'Connector' where there were no list. The List that contained the lists that would countain the Connectors was not added.

C# Downloading Program (Array)

I have a problem with my code. I want to download some files (I'm currently doing a patcher), but there are so many files, and I don't want to create a string for all of them.
I want to store the links in an array. But the debugger says there's and exception in WebClient. Here's my code (fájlNév means fileName and fájlNévAlap means baseFileName): UPDATED CODE:
<!-- language: lang-c# -->
WebClient myWebClient = new WebClient();
string[] remoteUrl = new string[2] { "https://www.dropbox.com/s/62tt9w194xefk7t/", " https://www.dropbox.com/s/spni307vmk4zng9/" };
string[] fájlNév = new string[2] { "alut.dll", "DevIL.dll" };
string fájlNévAlap = "BlackBox.dll", WebResource = null;
for(int i = 0; i < remoteUrl.Length; i++) {
for(int x = 0; x < fájlNév.Length; x++) {
WebResource = remoteUrl[i] + fájlNév[x];
MessageBox.Show(WebResource);
myWebClient.DownloadFile(WebResource,fájlNév[x]);
}
}
What can I do? What is wrong?
Many comments but not one mentioned this,
check out MSDN
public void DownloadFile(
string address,
string fileName
)
DownloadFile expect a file-name and not a folder.
Try changing to:
myWebClient.DownloadFile(WebResource,"C://" + fájlNév[x])
Moreover, writing directly to root folder might cause security exception, might be a good practice to write to a specific folder.
In addition, Xantham noted the loop will cause array out of bound exception.
Ofiris gave the main answer that a file-name is necessary, however there is a more mundane problem as well that I thought should be brought to attention.
The initial calls to the for loop:
for(int i = 0; i <= remoteUrl.Length; i++)
and
for(int x = 0; x <= fájlNév.Length; x++)
They will cause an array out of bounds exception as well, when it will try to look at remoteUrl[2], in an array of only 2 objects (0 and 1).

Categories