Get values from array and using the values in a program - c#

I have the code below which has created 2 arrays of integers from an input text file, I am trying to use the values from the 2 arrays to read a database using a stored procedure but I am getting this error:
Index was outside the bounds of the array.
Error is occuring when I run and debug program when it tries to assign
tests[x] = testId; in the code.
//read the error file
using (var reader = new StreamReader(#"D:\Temp\AccessError.txt"))
try
{
int testId = 0;
int eventId = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
//split the line
string[] parts = line.Split(new[] { "Event" }, StringSplitOptions.None);
//get valid integers
int[] tests = GetInts(parts[0].Split(' ', '\'')).ToArray();
int[] events = GetInts(parts[1].Split(' ', '\'')).ToArray();
foreach (int x in tests)
{
tests[x] = testId;
}
foreach (int y in events)
{
events[y] = eventId;
}
//stored proc to call database
SybaseAccess.GetPlans(aseConn, testId, eventId);
}
}

The error message is probably just what's going wrong: You're trying to access the array at an index that doesn't exist.
Let's say that you've parsed the numbers 1,2,3,4,5 from the line. These numbers are stored in the tests array, it has five elements. In this case the first four array accesses will work, but the fifth will fail, because the array has the indices 0,1,2,3,4
You should check if the numbers in tests don't exceed the length of the array.
Moreover I don't understand what exactly you are doing. You are parsing an array of numbers from a line ? And then you overwrite each of these numbers by replacing it with the testId ? That's rather complicated. If you want to have an array that contains n-times the testId as an integer, why not create that directly ?

Related

For a project I made 2 arrays, char[] and int[], they are the same size and I want the console to return a response

The objective is to return a binary value from the user input. in my mind, I thought that making an array or for loop that reads the response then chooses a corresponding index value and types the value into the console. With this, I get "Index was outside the bounds of the array". Help would be appreciated.
char[] letters = {'a','b','c',};
int[] binary = new int[26];
{
binary[0] = 01100001;
binary[1] = 01100010;
binary[2] = 01100011;
}
Console.WriteLine("Tell Me Something");
string sentence = Console.ReadLine();
int[,]outPut = new int[3,letters.Length];
for(int a = 0; a < outPut.Length;a++)
{
outPut[0,a] = binary[a];
Console.Write(outPut);
The for loop should be
for(int a = 0; a < letters.Length;a++)
The length of outPut array will be 9 as it is a 2D array.
You are looping from 0-8 and trying to assign it to outPut.
But outPut can only accept 3 numbers in the first row.
That is the reason you are getting the error

Updating line of a file if array element matches text box

I have a method which currently reads all lines of a directory file (3 fields per line) and updates a directory array with a record of text box entries if the extension code entered matches an extension code field in the file.
I had the updated directory array displaying to a list view, as soon as I attempted to update the directory file with the updated array, it all went downhill! Edit to clarify: with the latest version of the code below, the array no longer displays to the list view, and the file is not updated. No errors are thrown.
public void updateName()
{
int count = 0;
string[] lines = File.ReadAllLines(directoryFile);
// Set size of directory array equal to number of lines in file
int lineCount = lineCounter();
directory = new record[lineCount];
record currentRecord = new record();
// Iterate through each line in file
foreach (string line in lines)
{
// Split current line into three fields
string[] fields = line.Split(',');
// Save current line as new record with surname, forename and extCode fields
currentRecord.surname = fields[0];
currentRecord.forename = fields[1];
currentRecord.extCode = Convert.ToInt32(fields[2]);
// If extension code in current record matches text box entry
if (Convert.ToInt32(fields[2]) == Convert.ToInt32(txtExtCode.Text))
{
// Change surname and forname fields to match text box entries
currentRecord.surname = txtForename.Text;
currentRecord.forename = txtSurname.Text;
using (StreamWriter writer = new StreamWriter(directoryFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == count)
writer.WriteLine(currentRecord);
else
writer.WriteLine(lines[currentLine - 1]);
}
}
}
// Save currentRecord as next element in directory array, then increment
directory[count] = currentRecord;
count++;
}
}
You don't need a linecounter(). The number of lines is lines.Length.
But why do you need this directory array? You are filling it, but you are not using it anywhere.
Another major problem is that you are creating a StreamWriter inside the foreach loop. You should open the file before the loop and close it after the loop to make it work.
Also, you are mixing writing currentRecord which is of type record and writing lines of type string to the output file. This cannot work.
You are also putting txtForename.Text into currentRecord.surname instead of currentRecord.forename and vice versa.
I suggest to first apply the change in the lines array and then to write this lines array back to to file with File.WriteAllLines which is the symmetric operation to File.ReadAllLines.
I'm applying the change directly to fields array, so that I can convert it back to a string with String.Join (it is the symmetric operation to String.Split).
public void updateName()
{
// Do this conversion before the loop. We need to do it only once.
int selectedCode = Convert.ToInt32(txtExtCode.Text);
string[] lines = File.ReadAllLines(directoryFile);
for (int i = 0; i < lines.Length; i++)
{
// Split current line into three fields
string[] fields = lines[i].Split(',');
int extCode = Convert.ToInt32(fields[2]);
if (extCode == selectedCode)
{
fields[0] = txtSurname.Text;
fields[1] = txtForename.Text;
lines[i] = String.Join(",", fields);
// If the extension code is unique, leave the for-loop
break;
}
}
File.WriteAllLines(directoryFile, lines);
}
I also use for instead of foreach in order to have an index i, so that I can replace a single line in the lines array at a specific index.
I don't know if the extension code in the directory file is unique. If it is, you can exit the for loop prematurely with break.

How do I read a matrix from a file into an array

Hey guys Im trying to be able to save an array from a text file but I'm at my wits end trying to figure out how to save it. I can print all the elements of the matrix as can be seen from the text file.
Sample input:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
1 2 3 4 5
I keep getting an index out of range exception. Not sure what's happening.
Hopefully you guys understand what im trying to do.
Here's what I have so far:
class Program
{
static void Main(string[] args)
{
string input =
#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 5\Chapter 15 Question 5\TextFile1.txt";
StreamReader reader = new StreamReader(input);
List<string> list = new List<string>();
char[] unwanted = new char[] { ' ' };
using (reader)
{
int row = 0;
int column = 0;
string line = reader.ReadLine();
while (line != null)
{
string[] numbersString = line.Split(unwanted);
int[,] numbersInt = new int [ row, numbersString.Length];
foreach (string a in numbersString)
{
Console.Write("{0} ",a);// this is to check that the array was read in the right order
numbersInt[row, column] = int.Parse(a);
column++;
}
line = reader.ReadLine();
Console.WriteLine();
row++;
}
}
}
}
I suggest using jugged arrays (array of array int[][]) instead of 2D ones; in that case the solution will be quite simple, something like this (Linq):
int[][] matrix = File
.ReadLines(#"C:\myFile.txt")
.Split(new Char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(items => items
.Select(item => int.Parse(item))
.ToArray())
.ToArray();
Test (let's print out the matrix):
String report = String.Join(Environment.NewLine, matrix
.Select(line => String.Join(" ", line)));
Console.Write(report);
This change in your while should do the trick:
while (line = file.ReadLine()) != null)
{
...
}
Source: MSDN
You appear to be creating your instance of numbersInt inside your while loop. This means that with each pass of the loop you will re-create the array and when the loop exits the array will be lost. Move the declaration for numberInt to outside of the while loop.
Your immediate issue is that your code does not reset column back to zero after reading each line. Move int column = 0 into the while loop to fix this issue.
The second issue is numbersInt allocation. You create it for each line, which is not right, because it's a 2-D array. You need to create it before the loop, but of course you can't, because you don't know how many lines you are going to have. One approach is to use a dynamic data structure, and add one row at a time to it.
You can greatly simplify your code by using File.ReadAllLines method in combination with LINQ, because this would let you get rid of a lot of simple code. Now you can check how many lines you have before creating your 2-D array, and you could fill it in much easier as well:
var allRows = File
.ReadLines(#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 5\Chapter 15 Question 5\TextFile1.txt")
.Select(line => line.Split(unwanted).Select(int.Parse).ToList())
.ToList();
If you are OK with an array of arrays, you don't need to do anything: allRows is a 2-D structure of rows and columns containing your matrix.
If you must convert it to a 2-D array, you can do it with a pair of nested for loops:
if (allRows.Count == 0) {
// ... The file has no data - handle this error
}
var matrix = new int[allRows.Count, allRows[0].Count];
for (int row = 0 ; row != allRows.Count ; row++) {
for (int col = 0 ; col != allRows[0].Count ;col++) {
matrix[row, col] = allRows[row][col];
}
}

C# Array of List Index out of bounds

I've made a program that extracts some info from a file , do some operations with it and store it back on a list.
Following this link:
Are 2 dimensional Lists possible in c#?
I've been able to create a class with a list who would suit my needs. But after some debugging i've found that i was overwriting the list on each loop iteration.
Then i decided to make an array of lists - followed this link:
How to create an array of List<int> in C#?
Created an array of lists, initialized it and added elements. But when it needs to move to the next list position , it throws the out of boundaries exception.
I've tried a few things (readed about race condition) but none of 'em worked.
The problem will happen only when i open more than one file with my code ; otherwise it works perfectly.
Exception is thrown at xmldata , in the last iteration of the current file.
Ex: Selected two files, each one will add five elements. In the last element of the first file the exception will be thrown and there's data in the last element's position to be added.
Additional information: Index was outside the bounds of the array. (Exception thrown).
Any help will be appreciated. Thanks a lot.
Code:
List<xmldata>[] finalcontent = new List<xmldata>[9999];
finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename
foreach (Match m in matches)
{
Double[] numbers;
string aux;
aux = m.Groups[1].ToString();
aux = Regex.Replace(aux, #"\s+", "|");
string[] numbers_str = aux.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
numbers = new Double[numbers_str.Length];
for (int j = 0; j < numbers.Length; j++)
{
numbers[j] = Double.Parse(numbers_str[j], CultureInfo.InvariantCulture);
//Converts each number on the string to a Double number, store it in a position
//in the Double array
numbers[j] = numbers[j] / 100; //Needed calculus
numbers[j] = Math.Round(numbers[j], 3); //Storing numbers rounded
}
string values = String.Join(" ", numbers.Select(f => f.ToString()));
if (i <= colors_str.Length)
{
finalcontent[listpos].Add(new xmldata//The exception is thrown right here
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
}//Closing if
i++;
}//Closing foreach loop
Link to the file: https://drive.google.com/file/d/0BwU9_GrFRYrTT0ZTS2dRMUhIWms/view?usp=sharing
Arrays are fixed size, but Lists automatically resize as new items are added.
So instead, and since you're using Lists anyway, why not use a list of lists?
List<List<int>> ListOfListsOfInt = new List<List<int>>();
Then, if you really absolutely must have an array, then you can get one like this:
ListOfListsOfString.ToArray();
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
This is a big example, but check this one. You increase 'jx' before entering the statement, possibly exceeding the boundary of cnt?
Try changing the following:
if (i <= colors_str.Length)
to
if (i < colors_str.Length).
In fact I'm convinced that this is the problem.
This is because refereces begin at 0 and the last reference is length - 1, not length.
When using a list - it is better to use native functions for it.
List<xmldata>[] finalcontent = new List<xmldata>();
......
finalcontent[listpos] = new List<xmldata>(); insted of var _tmpVariable = new List<xmldata>();//Initializing a list for each filename
......
_tmpVariable.Add(new xmldata
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
fs.Close();//closing current file
listpos++;//Increment list position counter
finalcontent.Add(_tmpVariable); // add list into list
As there is no exception details it is hard to get where the exception is thrown.
It could be a list issue, a string issue or other (even file reading issue as well),
So please update this with current exception details.

"Index Out of Bounds" error when using the Split method for an Array

I am trying to split the data in this array, but it keeps giving me this error:
index out of bounds.
The size of the array is 10. The line of code that is creating the error is
int score = int.Parse(scoreInfo[1]);
This is the code that I have:
static void Main(string[] args)
{
const int SIZE = 10;
for (int j = 0; j < SIZE; j++)
{
// prompt the user
Console.WriteLine("Enter player name and score on one line");
Console.WriteLine("seperated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine();
// The split method creates an array of two strings
string[] scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type.
string name = (scoreInfo[0]);
int score = int.Parse(scoreInfo[1]);
if (inputStr == "")
{
Console.WriteLine(scoreInfo[j]);
}
}
Console.ReadLine();
}
A few things of note. You are using SIZE to denote how many iterations your loop should make. It is not the size of your array. Your array is only going to be large as the split makes it. If you split with a space as the delimiter, you're going to have 2 objects in the array at indices 0 and 1.
That last section where you're saying to write scoreInfo[j] will fail as soon as j is larger than 1.
I tried your code using a constant, something like "Guy 19". The .Split() method will break up your input string based on spaces. If you're not entering a space followed by a number, then your scoreInfo[1] will be empty and parsing will fail.
Try adding a break point after your .Split() to determine if scoreInfo is correctly split into a size 2 array, with [0] being the name of the player and [1] being an integer score. If you're entering a name like "FirstName LastName 20" then the information at position [1] is not going to be an integer and the parsing will also fail.
Your for-loop is sort of puzzling, are you looping through 10 times for a team of 10 players? You could put your dialog in a while loop and break out when parsing fails or the user types something like "exit".

Categories