Data cannot be assigned [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Hello why in this function data could not be read(assigned)?
Error is in the line with comments(Object reference not set to an instance of an object.)
protected static int[][] GetMapFromFile(ref int size)
{
using (StreamReader sr = new StreamReader(#"C:\Users\doman\OneDrive\Desktop\Antras semestras\Programavimas\Laboras1\Laboras1\Duomenys.txt"))
{
string skyr = " ,.;";
size = Convert.ToInt32(sr.ReadLine());
int[][] map = new int[size][];
for (int i = 0; i < size; i++)
{
string line = sr.ReadLine();
string[] values = line.Split(skyr.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < values.Length; j++)
{
map[i][j] = Convert.ToInt32(values[j]); // Error here
Console.Write(map[i][j]);
}
Console.WriteLine();
}
return map;
}
}
My data file
5
0 1 3 4 2
1 0 4 2 6
3 4 0 7 1
4 2 7 0 7
2 6 1 7 0

You need to create each "sub" array. Add map[i] = new int[values.Length] before the second for loop.

Related

How can I add int values to a c# array [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 2 years ago.
I have an array numArray with the length set to a value the user can put in. if arrayLength is 5 for example I want the for loop to count up by 1 to 5 [1,2,3,4,5]. My error is numArray[i] = sum + 1; (System.IndexOutOfRangeException: 'Index was outside the bounds of the array.')
int[] numArray = new int[arrayLength];
int sum = 0;
for (int i = 0; i <= arrayLength; i++)
{
Console.WriteLine(i);
numArray[i] = sum + 1;
}
Use i < arrayLength.
If i <= arrayLength at the last iteration i = 5 and you try to access numArray[5] which does not exists (you have only 5 indexes: 0 to 4 ).

C# array wont accept "size" [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
the noob, again. todays question is:
int[] forArray = new int[10];
for (int k = 1; k <= 10; k++)
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
it gives an "out of bounds" error. I would like my program to output natural numbers from 2 to 20. Instead gives off an error. when I change the first for loops condition to k <= 9 it runs but gives me 0 instead of 20. its like it returns the last value as 0 and "re-positions" it to the "front". sorry for the really simple question.
Arrays are zero-based, when it comes to referencing the elements. So, for 10 items in an array (which is what you allocated), it's forArray[0] through forArray[9]. Your code tries to loop from forArray[1] through forArray[10], and there is no index position 10 (which is when you end up going out of bounds).
Your second for-loop is fine, as it goes from 0 to 9.
Note: Since your loop needs to be zero-based, you'll need to adjust how you calculate the number you stuff into the index positions, if you want it starting with 2.
Debug your code and step through, as you see below you are trying to assign to index [10], which doesn't exist.
{
int[] forArray = new int[10];
for (int k = 1; k < 10; k++) // k < 10 instead of k <= 10
{
forArray[k] = k * 2;
Console.WriteLine(k); // test
//forArray[0] = SKIPPED
//forArray[1] = 2
//forArray[2] = 4
//forArray[3] = 6
//forArray[4] = 8
//forArray[5] = 10
//forArray[6] = 12
//forArray[7] = 14
//forArray[8] = 16
//forArray[9] = 18
//forArray[10] INVALID
}
for (int k = 0; k < 10; k++)
{
Console.WriteLine(forArray[k]);
}
}
Tested here
Change your condition to k
forArray[k - 1] = k * 2;

IndexOutOfRangeException error in C# after creating a double loop [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 6 years ago.
The following piece of code generates a IndexOutOfRangeException was unhandled, but I dont know why. The a for-loop is set to be smaller than the i for-loop because the array of arrays is 3x2. I did try to prey the i and a but with no luck. Can you see the error?
namespace text_test
{
class txt_program
{
// () You don't use "args" in the method
public void txt()
{
int[][] names = { new int[] { 2, 3, 4}, new int[] { 5, 6, 7} };
using (StreamWriter SW = new StreamWriter(#"txt.txt"))
{
for (int i = 0; i < 4; i++)
{
for (int a = 0; a < 3; a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}
}
}
}
}
The expected output would be a .txt file :
2 3 4
5 6 7
loop A repeated 4 times instead of 2 times
Instead of using magic numbers use GetLength()
for (int i = 0; i < names.GetLength(0); i++)
{
for (int a = 0; a < names.GetLength(1); a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}

Adding array to a list how to stop it being the last iteration data? [duplicate]

This question already has answers here:
C# dictionary value clearing out when I clear list previously assigned to it....why?
(6 answers)
Closed 6 years ago.
I am trying to create a list of an array of 2 items. The problem I have is the final iteration in my loop sets all the list's arrays to the same (my guess is due to a reference?). I was wondering how I can prevent this from happening.
This is what I am trying to do:
PathTiles[] links = new PathTiles[2];
int j;
for(int i = 0; i < path.Count; i++)
{
if(i+1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
for(j = i+1; j < path.Count; j++)
{
if(path[j].x == links[1].x && Mathf.Abs(path[j].y-links[1].y) == 1)
{
links[1] = path[j];
i = j;
}
else
{
break;
}
}
validPath.Add(links);
for(int k = 0; k < validPath.Count;k++)
{
Debug.Log(validPath[k].x+", "+validPath[k].y);
}
Debug.Log("=====");
}
}
So the console shows this:
0, 0
=====
1, 1 <-- why did this become 1, 1 and not stay as 0, 0
1, 1
=====
Does any one know how I can retain the first data value and not have it overwritten? I am currently under the impression it is because it stores a reference and so I changed the values, but I don't know how to stop it doing that.
Try adding the PathTiles[] links = new PathTiles[2]; within the 1st for loop statement. As you said this is a problem of references. As you were addiing the same modified links to the list. the 1st data value is overwritten.
int j;
for (int i = 0; i < path.Count; i++)
{
PathTiles[] links = new PathTiles[2]; //<-- here
if (i + 1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
...

Need some help on my exception handling

I want to create an exception handling to throw an error if the numbers of integers in each row are not equal to each other.
For example: Matrix = [ 3 4; 9 8 1] should be: matrix = [ 3 4 2; 9 8 1]
This is my code:
This is from my main, in which I create the string.
string text = "A = [8 5 5 4; 2 6 5 3; 8 5 2 6]";
This is my class:
public string[,] Matrix(string text)
{
char[] splitOne = { '[', ']' };
char[] splitTwo = { ';' };
char[] splitThree = { ' ' };
words = text.Split(splitOne)[1]
.Split(splitTwo, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(splitThree, StringSplitOptions.RemoveEmptyEntries))
.ToArray();
if (text.Split(';')[0].Replace(" ", " ").Length != text.Split(';')[1].Replace(" ", " ").Length)
{
Console.WriteLine("unbalanced matrix");
return null;
}
string[,] matrix = new string[words.Length, words[0].Length];
for (int i = 0; i < words.Length; ++i)
{
for (int j = 0; j < words[i].Length; ++j)
{
matrix[i, j] = words[i][j];
}
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write("{0} ", matrix[i, j]);
}
Console.WriteLine();
}
return matrix;
}
I added the if statement to do the exception handling. But it keeps on displaying the error message
Console.WriteLine("unbalanced matrix");
even when the matrix is a balanced matrix. I need some help with making this part of the code work. I try changing the 0 and 1 in the two brackets to 2 and 2 and it kind of works but not really.
The first two elements after Split: "8 5 5 4" and " 2 6 5 3", their Length being 7 and 8 respectively. Replacing spaces with spaces does nothing: Length is still 7 and 8. Also note that 100 3 and 1 2 3 have the same Length.
What you want to check is if each element of Split(';') which was then Split(' ') has the same Length (4 in the first example, and 2 and 3 in my second example). You would also want to do it in a loop, because testing just first two rows does not protect you from [1 2; 3 4; 5 6 7 8].
Finally, Console.WriteLine is not throwing an exception, which is what I suppose you should be doing in this exercise, given the wording of your task: you need throw. Learn more about exceptions here.

Categories