I hope all of you are having a nice day. So I fixed one error of my program but there's another :/
So here's the code where I create my and read the data from a file:
void ReadData(string fileName, Branch[] branches)
{
string shopsName = null;
using (StreamReader reader = new StreamReader(#fileName))
{
string line = null;
line = reader.ReadLine();
if (line != null)
{
shopsName = line;
}
Branch tempBranches = TempBranch(branches, shopsName);
string address = reader.ReadLine();
string phoneNumber = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
string facturer = values[0];
string model = values[1];
double capacity = double.Parse(values[2]);
string energyClass = values[3];
string assemblyType = values[4];
string color = values[5];
string attribute = values[6];
double cost = double.Parse(values[7]);
Fridges fridge = new Fridges(facturer, model, capacity, energyClass, assemblyType, color, attribute, cost);
tempBranches.fridges.AddFridge(fridge);
}
}
And there's the code where I use the TempBranch method. The error is in this line: if (branches[i].ShopsName == shopsName). Hopefully you can help me, cuz I was trying to fix this yesterday for 30 minutes and it still wasn't working :D
private static Branch TempBranch(Branch[] branches, string shopsName)
{
for (int i = 0; i < MaxNumberOfFridges; i++)
{
if (branches[i].ShopsName == shopsName)
{
return branches[i];
}
}
return null;
}
If you replace MaxNumberOfFridges with branches.Length it will only try to find a Branch that's within the range of the branches array. The reason it's not working is because you're trying to access an index which is greater than the Length of the array.
Try this one. Use foreach, if you dont know the lenght of array.
private static Branch TempBranch(Branch[] branches, string shopsName)
{
foreach(var branch in branches)
{
if (branch.ShopsName == shopsName)
{
return branch;
}
}
return null;
}
You can also try to make use of a LINQ query,
return branches.Where(b => b.ShopsName == shopsName).FirstOrDefault();
EDIT:
To NullReferenceError which occurs in your new post occurs due to null being returned in your function where your shop gets created. This due to not finding the given shopname.
So it tries to add an fridge to an shop which does not exist, which is not possible. You will have to add a check so that this does not occur.
This raised error because MaxNumberOfFridges is bigger than branches length.. to simplify it, assume MaxNumberOfFridges is 20 but arry length is 10, so you are trying to access element 11 in array which is outside of array length.
to fix it
for (int i = 0; i < branches.Length; i++)
{
if (branches[i].ShopsName == shopsName)
{
return branches[i];
}
}
other option is to use foreach loop
foreach(var b in branches)
{
if (b.ShopsName == shopsName)
{
return branches[i];
}
}
so I wrote some C# code and I am trying to test it incrementally, do to something that would take a while to explain, but bottom line, I'm new to c# and not understanding the online compiler error messages. Here is the error message I get when I try and compile, but the strings look good to me.
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
string[] solutionSetArray = new string[12];
string ret = "";
string delimeter = "|";
int tempPos = 0;
int counter = 0;
int successFlag = 0;
int patternLength = 5;
for (int index = 0; index < solutionSet.Length; index++)
{
if (solutionSet[index] == delimeter)
{
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
tempPos = index + 1;
counter++;
}
if (solutionSet.Length - index == 1)
{
solutionSetArray[solutionSetArray.Length-1] = solutionSet.Substring(tempPos, solutionSet.Length);
}
}
for (int i = 0; i < patternLength; i++)
{
Random rnd = new Random();
int randIndex = rnd.Next(solutionSetArray.Length);
if (i != patternLength - 1)
{
ret += solutionSetArray[randIndex] + "|";
successFlag++;
}
else
{
ret += solutionSetArray[randIndex];
}
}
if (successFlag == patternLength - 1)
{
Console.WriteLine(ret);
}
else
{
Console.WriteLine("ERROR");
}
The error (which, according to the message, is on line 1, column 11) is being caused by your very first line of code, which begins string.
I can't tell the context from just your post, but my guess is that you are declaring solutionSet in a block that is not inside of a class or function. You should enclose your code in a class or method, e.g.
public class MyClass
{
static public void Main()
{
string solutionSet = "white|black|beige|pink|green|blue|red|yellow|orange|cyan|purple|brown";
//Rest of code goes here
}
}
By the way, if you're trying to convert solutionSet to an array, you can just write
var solutionSetArray = solutionSet.Split("|");
the problem with your code is
solutionSetArray[counter] = solutionSet.Substring(tempPos, index);
after 6 iterations tempPos=34 and index=37 which is running out of bounds of solutionSet. I would suggest to use var solutionSetArray = solutionSet.Split("|"); and also use LinqPad which can be easy for you to debug if possible,.
I'm attempting to import a CSV file into a DataTable, however the CSV contains headers that are the same. (For example, there are multiple "Date" headers for different form sections). To fix this, I decided to create a loop that will run through the headers and replace the duplicates or unwanted entries based on their position. I've replaced my replaceWith array with dummy entries, but my actual code does have the correct size to correlate with the replace array.
string[] columnNames = null;
string[] oStreamDataValues = null;
int[] error = {0,1,2,3,4,7,8,9,10,11,15,21,34,37,57,61,65,68,69,71,75,79,82,83,85,89,93,96,97,99,103,107,110,111,113,117,121,124,125,127,128,129,130,132,182,210,212,213,214,215,216,222,226,239};
int[] replace = {14,16,17,17,20,23,24,27,28,29,31,32,44,58,59,60,62,63,64,66,67,70,72,73,74,76,77,78,80,81,84,86,87,88,90,91,92,94,95,98,100,101,102,104,105,106,108,109,112,114,115,116,118,119,120,122,123,126,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,184,186,187,188,190,191,192,194,195,196,198,199,200,202,203,204,206,207,208,209,236,242,243,244};
string[] replaceWith = {"Replace 1", "Replace 2", "Replace 3"};
string fix = "ignore_";
int inc = 00;
string entry = "";
while (!oStreamReader.EndOfStream)
{
string oStreamRowData = oStreamReader.ReadLine().Trim();
if (oStreamRowData.Length > 0)
{
//oStreamDataValues = Regex.Split(oStreamRowData, ",(?=(?:[^']*'[^']*')*[^']*$)");
oStreamDataValues = oStreamRowData.Split(',');
if (rowCount == 0)
{
rowCount = 1;
columnNames = oStreamDataValues;
for (int i = 0; i < columnNames.Length; i++)
{
for (int j = 0; j < error.Length; j++)
{
if (error[j] == i)
{
entry = fix + inc++;
}
}
for (int k = 0; k < replace.Length; k++)
{
if (replace[i] == i)
{
int add = 0;
entry = replaceWith[add++];
}
}
DataColumn oDataColumn = new DataColumn(entry, typeof(string));
oDataColumn.DefaultValue = string.Empty;
oDataTable.Columns.Add(oDataColumn);
}
}
}
I'm no coding expert, so my syntax/decision making isn't perfect.
However the error that I get is that A column named 'ignore_4' already belongs to this DataTable.
I assume something is incorrect in my loop logic.
I think you have overcomplicated the loops. You just need to keep an index of the current position in the array of errors and array of replaces.
string rep = "replace_"; // base string for replace fields
string fix = "ignore_"; // base string for ignore fields
// For demonstation purpose I have commented out this array. If you
// want every 'replace' column have its specific name then prepare this
// array with exactly the number of names required by the number of
// elements in the replace array
//
// string[] replaceWith = {"Replace 1", "Replace 2", "Replace 3"};
int idxErrors = 0; // Current position in the error array
int idxReplace = 0; // Current position in the replace array
int fixCounter = 1;
int repCounter = 1;
string entry = "";
for (int i = 0; i < columnNames.Length; i++)
{
// Is this the index of a column that should be ignored?
if (idxErrors < error.Length && i == error[idxErrors])
{
entry = fix + fixCounter.ToString("D2");
idxErrors++;
fixCounter++;
}
// Is this the index of a column that should have a different name??
else if (idxReplace < replace.Length && i == replace[idxReplace])
{
entry = rep + repCounter.ToString("D2");
// entry = replaceWith[repCounter];
idxReplace++;
repCounter++;
}
else
entry = columnNames[i];
// Now create the column
DataColumn oDataColumn = new DataColumn(entry, typeof(string));
oDataColumn.DefaultValue = string.Empty;
oDataTable.Columns.Add(oDataColumn);
}
In this example I have used the same pattern used for the ignored column also for the columns that need to have the name changed. If you want to give each renamed column a proper name, then you need to prepare an array with these proper names and this array should be of the same length of the replace array. Then use the idxReplace to take the correct name from the array of possible proper names.
everyone,
now i'm writing a C# programm according to a piece of matlab code.
In matlab code there are two commands to read data from the COM-Port:
A=fscanf(com_Port1,'%s');
A=fread(com_Port1,1008); //two sentences are next to each other like i write here.
For the first command "A=fscanf(com_Port1,'%s');" i used:
string A = com_Port1.ReadExisting();
and it seems all right, because no error warning;
for the second command "A=fread(com_Port1,1008);" i used:
double[] B = new double[1008];
for (int i = 0; i <= 1008 - 1; i++)
{
B[i] = com_Port1.ReadByte() ;
}
then it shows an error:
"A first chance exception of type 'System.TimeoutException' occurred
in System.dll".
So i'm assuming that "ReadExisting" has read all the data, and "ReadByte" can't read available data any more, is that right?Could someone tell me where i war wrong? thank you.
Yours
Adam
Add at Nov.20.2013, below is the code i have wrote, i have tried "Read()","ReadTo()","ReadLine()", but i still get the error at "otdr_Portobject.ReadByte()", i have no idea any more.
otdr_Portobject = new otdr_Port(cB_portNames.SelectedItem.ToString());
otdr_Portobject.Open();
btn_Stop.Enabled = true;
btn_Start.Enabled = false;
/*if (!otdr_Portobject.IsOpen)
{
MessageBox.Show("not open");
}
else {
MessageBox.Show("Serial Port opened");
};*/
//string start = "start";
otdr_Portobject.Write("start");
char[] b9 = new char[7];
otdr_Portobject.Read(b9, 0, 7);
Thread.Sleep(5000);
//string isready = "isready";
otdr_Portobject.Write("isready");
char[] b10 = new char[10];
otdr_Portobject.Read(b10, 0, 10);
//A = otdr_Portobject.ReadTo("\n");
//string rdatb = "rdatb";
int int32_Auslesekommando = Convert.ToInt32(pointsCon.Value-1);
otdr_Portobject.Write("rdatb " + int32_Auslesekommando.ToString("X4") + "\n");
Thread.Sleep(50);
char[] b11 = new char[18];
otdr_Portobject.Read(b11, 0, 18);
//A = otdr_Portobject.ReadTo("\n");
//A = otdr_Portobject.ReadTo("\n");
//int A1=otdr_Portobject.ReadByte();
//brechnen Y Axis
int pointNum = Convert.ToInt32(pointsCon.Value);
double[] B = new double[pointNum];
//int byteNum=otdr_Portobject.BytesToRead;
//if ( byteNum== 0) return;
try
{
for (int i = 0; i <= pointNum - 1; i++)
{
B[i] =System.Convert.ToDouble( otdr_Portobject.ReadByte() )* 256;
}
}
catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
From the c#-docs:
ReadExsting: Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object..
MATLAB:
%s format for fscanf: Read series of characters, until find white space.
So you should probably switch to ReadTo, specifying a white-space character to stop.
Or call Read yourself until the returned value is a whitespace-character.
I want to publish server-messages on Twitter, for our clients.
Unfortunately, Twitter only allows posting 140 Chars or less. This is a shame.
Now, I have to write an algorithm that concatenates the different messages from the server together, but shortens them to a max of 140 characters.
It's pretty tricky.
CODE
static string concatinateStringsWithLength(string[] strings, int length, string separator) {
// This is the maximum number of chars for the strings
// We have to subtract the separators
int maxLengthOfAllStrings = length - ((strings.Length - 1) * separator.Length);
// Here we save all shortenedStrings
string[] cutStrings = new string[strings.Length];
// This is the average length of all the strings
int averageStringLenght = maxLengthOfAllStrings / strings.Length;
// Now we check how many strings are longer than the average string
int longerStrings = 0;
foreach (string singleString in strings)
{
if (singleString.Length > averageStringLenght)
{
longerStrings++;
}
}
// If a string is smaller than the average string, we can more characters to the longer strings
int maxStringLength = averageStringLenght;
foreach (string singleString in strings)
{
if (averageStringLenght > singleString.Length)
{
maxStringLength += (int)((averageStringLenght - singleString.Length) * (1.0 / longerStrings));
}
}
// Finally we shorten the strings and save them to the array
int i = 0;
foreach (string singleString in strings)
{
string shortenedString = singleString;
if (singleString.Length > maxStringLength)
{
shortenedString = singleString.Remove(maxStringLength);
}
cutStrings[i] = shortenedString;
i++;
}
return String.Join(separator, cutStrings);
}
Problem with this
This algorithm works, but it's not very optimized.
It uses less characters than it actually could.
The main problem with this is that the variable longerStrings is relative to the maxStringLength, and backwards.
This means if I change longerStrings, maxStringLength gets changed, and so on and so on.
I'd have to make a while loop and do this until there are no changes, but I don't think that's necessary for such a simple case.
Can you give me a clue on how to continue?
Or maybe there already exists something similar?
Thanks!
EDIT
The messages I get from the server look like this:
Message
Subject
Date
Body
Message
Subject
Date
Body
And so on.
What I want is to concatenate the strings with a separator, in this case a semi-colon.
There should be a max length. The long strings should be shortened first.
Example
This is a subject
This is the body and is a bit lon...
25.02.2013
This is a s...
This is the...
25.02.2013
I think you get the idea ;)
Five times slower than yours (in our simple example) but should use maximum avaliable space (no critical values checking):
static string Concatenate(string[] strings, int maxLength, string separator)
{
var totalLength = strings.Sum(s => s.Length);
var requiredLength = totalLength - (strings.Length - 1)*separator.Length;
// Return if there is enough place.
if (requiredLength <= maxLength)
return String.Concat(strings.Take(strings.Length - 1).Select(s => s + separator).Concat(new[] {strings.Last()}));
// The problem...
var helpers = new ConcatenateInternal[strings.Length];
for (var i = 0; i < helpers.Length; i++)
helpers[i] = new ConcatenateInternal(strings[i].Length);
var avaliableLength = maxLength - (strings.Length - 1)*separator.Length;
var charsInserted = 0;
var currentIndex = 0;
while (charsInserted != avaliableLength)
{
for (var i = 0; i < strings.Length; i++)
{
if (charsInserted == avaliableLength)
break;
if (currentIndex >= strings[i].Length)
{
helpers[i].Finished = true;
continue;
}
helpers[i].StringBuilder.Append(strings[i][currentIndex]);
charsInserted++;
}
currentIndex++;
}
var unified = new StringBuilder(avaliableLength);
for (var i = 0; i < strings.Length; i++)
{
if (!helpers[i].Finished)
{
unified.Append(helpers[i].StringBuilder.ToString(0, helpers[i].StringBuilder.Length - 3));
unified.Append("...");
}
else
{
unified.Append(helpers[i].StringBuilder.ToString());
}
if (i < strings.Length - 1)
{
unified.Append(separator);
}
}
return unified.ToString();
}
And ConcatenateInternal:
class ConcatenateInternal
{
public StringBuilder StringBuilder { get; private set; }
public bool Finished { get; set; }
public ConcatenateInternal(int capacity)
{
StringBuilder = new StringBuilder(capacity);
}
}