adding element in a list throws ArgumentOutOfRangeException - c#

My code throws this:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index error
When it finds an element in a list that have a count less that a specific number. any ideas on how to correct the code?
I've added debug.log code everywhere to determine exactly where the error happens, because no error is underlined by Visual Studio.
List<int> emptyRows = new List<int>();
for (int j = 0; j < gridPositions.Count; j++) // try to find if a row is still empty
{
Debug.Log("gridPositions[" + j + "].Count is " + gridPositions[j].Count);
Debug.Log("columns are" + columns);
if (gridPositions[j].Count == columns)
{
Debug.Log("trying to add to emptyrows");
emptyRows.Add(j);
Debug.Log("added to emptyrows and its count is " + emptyRows.Count);
}
else
{
Debug.Log("found an occupied row at row " + j);
//ERROR STRIKES HERE
}
Debug.Log("emptyRows is " + emptyRows[j]);
Debug.Log("emptyRows count is " + emptyRows.Count);
}
I expect the emptyRows to track and record all unoccupied rows, but when it fills an occupied row, it not proceeds whit the for loop and stops.

You are only adding to emptyRows if (gridPositions[j].Count == columns)
But you are accessing the emptyRows[j] on every value of j
So the emptyRows ends up having less items then the value of j is

Related

Join string to 2d array, which already contains string or null

I would like to create code, to join few text files (each one has different structure) into one with unifying build.
For now, I manage to open all files, split strings in rows by tabulator and save everything into one two dimensional lists.
Example of current data:
809187.49 226885.80 26934
809183.14 226877.21 26937a
2 5509514.58 6558911.86 0.00 80T
3 5509515.55 6558913.48 0.00 80T
4 5509516.35 6558914.56 0.00 80T
Next, I am going to reprint content from a two-dimensional list into a new array (with n rows and 2 columns) and sort all data at the same time. All double type, greater then 100000.00 I want to put into the second column with ',' separator and the rest of content of each row from the list I would like to put into the first column:
Result:
26934 809187.49,226885.80
26937a 809183.14,226877.21
2,0.00,80T 5509514.58,6558911.86
3,0.00,80T 5509515.55,6558913.48
4,0.00,80T 5509516.35,6558914.56
And here is the problem. I used code like below:
string[,] resultArray = new string[RowNo, 2]; //Create Array
for (int i = 0; i < resultList.Count; i++)
{
for (int j = 0; j < Regex.Matches(file[i], " ").Count+1; j++)
{
if (double.TryParse(resultList[i][j], out n)) // record is a double type greater then n
{
if((Double.Parse(resultList[i][j]) % 1) > 0) // record is not a int type
{
if (resultArray[i, 1] != null) // if cell in array is not null
{
resultArray[i, 1].Insert(resultArray[i, 1].Count(), "," + resultList[i][j].ToString()); // add content of List in to string in second column
}
else // if cell in array is null for now
{
resultArray[i, 1].Insert(0, "," + resultList[i][j].ToString()); // put content of List in to second column
}
}
if (resultArray[i, 0] != null) //if cell in array is not null
{
resultArray[i, 0].Insert(resultArray[i, 0].Count(), ";" + resultList[i][j].ToString()); // put content of List in to first column
}
else // if cell in array is null for now
{
resultArray[i, 0].Insert(0, "," + resultList[i][j].ToString()); // put content of List in to first column
}
}
else
{
if (resultArray[i, 0] != null) //if cell in array is not null
{
resultArray[i, 0].Insert(resultArray[i, 0].Count(), ";" + resultList[i][j].ToString()); // put content of List in to first column
}
else // if cell in array is null for now
{
resultArray[i, 0].Insert(0, "," + resultList[i][j].ToString()); // put content of List in to first column
}
}
}
}
But unfortunately, when I run code I receive bug "Object reference not set to an instance of an object"
I have make some research and try something like this:
resultArray[i, 1] += resultArray[i, 1] + "," + res_file[i][j].ToString();
instead
resultArray[i, 1].Insert(resultArray[i, 1].Count(), "," + res_file[i][j].ToString());
But it wasn't work correctly. I received some results but data in record was duplicated.
I will appreciate every help.
The problem is with all your else conditions:
You are doing
if (resultArray[i, 0] != null) //if cell in array is not null
{
resultArray[i, 0].Insert(resultArray[i, 0].Count(), ";" + resultList[i][j].ToString()); // put content of List in to first column
}
else // if cell in array is null for now
{
resultArray[i, 0].Insert(0, "," + resultList[i][j].ToString()); // put content of List in to first column
}
which basically means do if block when resultArray[i, 0] != null, but in the else block you are trying to access the Insert() method of that null object. Hence the error. All of your else blocks are like that.
I think what you want to do is an assignment in your else blocks (which you seem to have figured out)... like:
resultArray[i, 0] += "," + resultList[i][j].ToString());
The problem with duplicates may have been that you are using both += and the left hand side (LHS) expression in
resultArray[i, 1] += resultArray[i, 1] + "," + res_file[i][j].ToString();
When you do x += 1; it is same as x = x + 1;
You are doing: x += x + 1; which is same as x = x + (x + 1);

c# dictionary automatically break the for loop,

Dictionary<double, Tuple<int,int>> dictionary = new Dictionary<double, Tuple<int,int>>();
for (int i = 0; i < x.Length; i++)
for (int j = i+1; j < x.Length; j++)
{
double weight = Math.Round(Math.Sqrt(Math.Pow((x[i] - x[j]), 2) + Math.Pow((y[i] - y[j]), 2)), 2);
string edges = i + "-" + j + "-" + weight;
listBox1.Items.Add(edges);
Tuple<int, int> tuple = new Tuple<int, int>(i, j);
dictionary.Add(weight, tuple);
}
var list = dictionary.Keys.ToList();
list.Sort();
foreach (var key in list)
{
string a = dictionary[key].Item1 + "--" + dictionary[key].Item2 + "--> " + key.ToString();
listBox2.Items.Add(a);
}
I am trying to store some values in dictionary. But in the for loop suddenly its break with uncomplete values. There is no error message.
When i comment out "dictionary.Add(weight, tuple);" listbox is showing all data i want.
If you try to Add to a Dictionary a key which was already added, it'll throw a DuplicateKeyException. This is highly likely since you're rounding your double, resulting in several which will become the same value.
Assuming by the use of a ListBox that you're using this in a UI event (Forms, WPF, or otherwise) I would say it probably is throwing an exception, but something else is catching that exception and moving on.
When adding to a dictionary, you should check if the key already exists, and handle appropriately.
If you want to override the value, keep in mind that this[TKey key] will not throw an exception when adding a new item. Thus
// dictionary.Add(weight, tuple);
dictionary[weight] = tuple;
If you want to skip past a value that's already present, check for ContainsKey
if(!dictionary.ContainsKey(weight))
dictionary.Add(weight, tuple);

How do I check if my array contains my guessed numbers respectively?

If my array contains random numbers in respective order (1,2,3,4,5,6,7) and I want to create another array of my guesses (1,4,2,4,5,6,7), I would like to see how many I got correct, respectively.
Here's my code:
Console.WriteLine("Can you guess the numbers that have appeared on the screen respectively?");
for (int i = 1; i < num.Length; i++)
{
Console.Write(i + ". ");
string temp = Console.ReadLine();
userGuess[i] = Convert.ToInt32(temp);
}
for (int i = 1; i < num.Length; i++)
{
if (num[i] == userGuess[i])//Here's my problem. I am unable to
//test whether my guess resides in the num array.
{
count++;
}
}
Console.WriteLine("You got " + count + " guesses right.");
Count should end up with 5 correct if I was to choose 1,4,2,4,5,6,7, judging that my num array contains 1,2,3,4,5,6,7 respectively.
Thanks!
Like #failedprogramming said, you missmatch index between array userGuess and num.
I know you want to start user input with no."1" but, it will get your userguess array will be moving in wrong index.
1 2 3 4 5 6 7
blank 1 4 2 4 5 6
So, you have no right answer.
Maybe you can use this:
Console.WriteLine("Can you guess the numbers that have appeared on the screen respectively?");
for (int i = 1; i < num.Length+1; i++)
{
Console.Write(i + ". ");
string temp = Console.ReadLine();
userGuess[i-1] = Convert.ToInt32(temp);
}
for (int i = 0; i < num.Length; i++)
{
if (num[i] == userGuess[i])//Here's my problem. I am unable to
//test whether my guess resides in the num array.
{
count++;
}
}
Console.WriteLine("You got " + count + " guesses right.");
Since the two arrays are of equal length, you can use LINQ's Zip() method:
var result = num.Zip(userGuess, (n, u) => n == u ? 1 : 0).Sum();
This compares each corresponding element in the two lists, returning 1 for a match or 0 for a non-match, then adds up the values. The result is effectively the number of matches.

Populate an array element with 2 datarows at a time

i want to populate an array element with 2 datarows at a time.
i am using javascript pausescroller and on every single array element i want to show 2 Rows in the scroller.
sample code is
Datatable tblNews;
for(int i = 0; i < tblNew.Rows.Count; i++)
{
array[i] = tblNews.Rows[i][""].ToString() + "" + tblNews.Rows[i + 1][""].ToString();
}
but problem is i am getting error that no row found at position 1;
Any solution guys
Yah, quite simply, when you're getting to the end of your tblNew.Rows.Count you're adding another one and that doesn't exist in your rows...
so a quick and dirty fix...
for(int i = 0; i < tblNew.Rows.Count-1; i++)
{
// do a quick check to make sure there is a row there to get data from
string addMe = i + 1 <= tblNews.Rows.Count-1 ? tblNews.Rows[i+1][""].ToString() : "";
array[i] = tblNews.Rows[i][""].ToString() + "" + addMe;
}

How to check the missing element in the sequence

I am doing a project related to payroll where i will have some payperiodnumbers for each and every payroll that has been runned. I will show all the payrolls in a grid view with the corresponding pay period numbers.
Assume i get the following results when i binded to grid
Now from the grid if i select 1 and click on delete i would like to show an error message stating you have to delete max pay period first.
Like that if i had my max pay period number as 7 and if user selects 1,2,3,4,5,6 and try to delete i would like to display the same error. I am saving the selected ID's in a arraylist so can any one help me how can i check for my condition as specified. I can get the maximum payperiodid using the query but the remaining code i would like to do.
I am using 2.0 so no point of using LINQ here. Can any one help me
As Azodious pointed i am showing some condition that should work and some not
If max number is 7 and if i select 1,5,7 i would like to display an error message.
If i select 5,6,7 then it should delete that.
Something like this:
selectedNumbers.Sort();
selectedNumbers.Reverse();
int maxPeriodNumber = 5; // This you know
int lastValue = (int)selectedNumbers[0];
if (lastValue < maxPeriodNumber)
{
// Highest selected number is smaller than required, warn user or throw exception
return;
}
foreach (int val in selectedNumbers)
{
if (val < (lastValue - 1))
{
// There is a gap in the numbering, warn user or throw exception
return;
}
lastValue = val;
}
// When you end up here, everything is ok and you can delete the items whose numbers are in the list
A simple logic to display missing numbers
ArrayList a = new ArrayList();
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(3);
lst.Add(5);
int fst = (int)lst[0];
int last = 0;
for (int i = 0; i < lst.Count; i++)
{
last = (int)lst[i];
}
for (int k = fst; k <= last; k++)
{
if (k == fst | k == last)
{
}
else
{
a.Add(k);
a.Add(" ");
}
}
Label1.Text = "Missing Numbers are" + " " + System.String.Concat(a.ToArray());

Categories