Array of string not working - c#

I use a simple array: contentHouseOne[] that contains strings. But in the Do/While loop it isn't working! It seems like the code don't understand that it's a string when a new object is to be created!? It works when I hardcode the string like I show below. Help is preciated! Thanks!
This isn't working:
listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition));
But this works:
listHouseParts.Add(new HousePart(content, "100x100", newPosition));
EDIT:
Here are some code to declare arrays
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
bool[,] occupiedPositions = new bool[500,500];
Here are some code to set all grid positions to false
for (int i = 0; i < gridCol; i++)
for (int ii = 0; ii < gridRow; ii++)
occupiedPositions[i, ii] = false;
And finally here are the code that I have the problem
int i = 0;
do
{
Vector2 newPosition = NewRandomPosition;
if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false)
{
listHouseParts.Add(new HousePart(content,
contentHouseOne[i], newPosition));
occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true;
i++;
}
}
while (i <= 5);

Your string array includes five elements:
string[] contentHouseOne = new string[] { "ruta100x100Red",
"ruta100x100Grey",
"ruta100x100Green",
"ruta100x100Yellow",
"ruta100x100Blue" };
But your while loop ends if your running variable i is greater than 5
while (i <= 5);
which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined.
You should change your while condition to (i < 5).

Try this so atleast you know if its empty or not
HousePart housePart = new HousePart();
housePart.Content = content;
if (!string.IsNullOrEmpty(contentHouseOne[i]))
housePart.ContentHouseOne = contentHouseOne[i];
else
housePart.ContentHouseOne = string.Empty;
housePart.NewPosition = newPosition;
listHouseParts.Add(housePart);

Related

C# Append at last line a character on all then one by one?

I'm making console c# app that actually takes all lines from text1 and append to it in the end of each line a text that is ".php?" or ".html? and these texts are also lines from text2, I want to print the first one in text2 in the end of each line in text1. Then take the second one in text2 and do the same Until it finishes text2?
Here's my code:
string[] resultConfig = File.ReadAllLines("keywords.txt");
string[] readParameters = File.ReadAllLines("param.txt");
for (int i = 0; i < readParameters.Length; i++)
{
for (int x = 0; x < resultConfig.Length ; x++)
{
resultConfig[x] = resultConfig[x] + readParameters[i];
Console.WriteLine(resultConfig[x]);
}
}
OUTPUT:
**
keyboards.php?.html?.asp?
karachi.php?.html?.asp?
keychain.php?.html?.asp?
in khobar.php?.html?.asp?
lebanon.php?.html?.asp?
lights.php?.html?.asp?
london.php?.html?.asp?
must have.php?.html?.asp?
**
**
WHAT IT SHOULD BE:
keyboards.php?
karachi.php?
keychain.php?
in khobar.php?
lebanon.php?
lights.php?
london.php?
must have.php?
keyboards.html?
karachi.html?
keychain.html?
in khobar.html?
lebanon.html?
lights.html?
london.html?
must have.html?
**
etc...
** KEYWORDS.TXT CONTAINS **
keyboards
karachi
keychain
in khobar
lebanon
lights
london
must have
** PARAM.TXT CONTAINS **
.php?
.asp?
.html?
Your problem is this line resultConfig[x] = resultConfig[x] + readParameters[i];. In this line you change your string in resultConfig[x] and since you're using a nested loop, this happens for every line in your *param.txt` file.
In order to write you desired result in the console try this code instead:
string[] resultConfig = File.ReadAllLines("keywords.txt");
string[] readParameters = File.ReadAllLines("param.txt");
for (int i = 0; i < readParameters.Length; i++)
{
for (int x = 0; x < resultConfig.Length ; x++)
{
string line = resultConfig[x] + readParameters[i];
Console.WriteLine(line);
}
}
You keep adding the parameter to the config and you should change the order of the loops and not change the value in the array.
Something like this:
string[] resultConfig = File.ReadAllLines("keywords.txt");
string[] readParameters = File.ReadAllLines("param.txt");
for (int x = 0; x < resultConfig.Length ; x++)
{
for (int i = 0; i < readParameters.Length; i++)
{
Console.WriteLine(resultConfig[x] + readParameters[i]);
}
}
It appears you want to save all these results in the resultConfig array, but you can't just add more items to an array than it was initialized with - you have to resize it first using Array.Resize(ref resultConfig, resultConfig.Length * readParameters.Length).
However, even then it will be a little tricky to append to the first set of items and then add new items for the additional parameters (it can be done if that's really necessary).
Instead I would create a new List<string> to save the results, and leave the initial arrays as they are:
string[] resultConfig =
{
"keyboards",
"karachi",
"keychain",
"in khobar",
"lebanon",
"lights",
"london",
"must have"
};
string[] readParameters = {".php?", ".html?", ".asp?"};
var allCombinations = new List<string>();
for (int i = 0; i < readParameters.Length; i++)
{
for (int x = 0; x < resultConfig.Length; x++)
{
allCombinations.Add(resultConfig[x] + readParameters[i]);
Console.WriteLine(resultConfig[x] + readParameters[i]);
}
}

New to c#, not understanding online compiler

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,.

name is not incrementing by 1 after number 45

i am trying to add a location name to my output text files.
As you can see my numbers are incrementing properly. But i have coded like after number 45 i need to reset the number to 1, also the Carousel:45 should change to ** Carousel1:1**. But it is not happening... why it is not happening. any help please!!!!
My code snippet:
public void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string CarouselName = enter.Text;
int[] cols = new int[] { 15, 15, 25, 15, 15 };
StringBuilder sb = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));
sb.AppendLine("Location".PadRight(15));
sb.AppendLine();
int tmpCarousel = 0;
int carouselNumber = 0;
Dictionary<string, int> namesForCarousels = new Dictionary<string, int>();
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
sb.Append(textfile[i].Cells[c].Replace(" ", "_").PadRight(cols[c]));
string name = textfile[i].Cells[1];
if (namesForCarousels.TryGetValue(name, out tmpCarousel) == false)
{
carouselNumber++;
if (carouselNumber > 45)
carouselNumber = 1;//resetting to number1, but name is
//not changing to Carousel1..
namesForCarousels[name] = carouselNumber;
}
var strCorousel = lstMX.Find(x => x.MAX_PN.Equals(name)).Carousel;
strCorousel = (String.IsNullOrEmpty(strCorousel)) ? CarouselName : strCorousel;
sb.Append(String.Format("{0}:{1}", strCorousel, carouselNumber).PadRight(15));
sb.Append("\r\n");
}
System.IO.File.WriteAllText(#"Z:\Desktop\output.TXT", sb.ToString());
}
OUTPUT i need
I need after Carousel:45 >>> i need Carousel1:1. How can i do this..?
You never use the numbers stored in your dictionary namesForCarousels after setting them. Probably you want
sb.Append(String.Format("{0}:{1}", strCorousel, namesForCarousels[name]).PadRight(15));
Also, you should rename carouselNumber to something like carouselNumberCounter. It's not the number of the current carousel, it's a counter used to assign a number to the next carousel. And for additional clarity, get rid of the local variable tmpCarousel and do:
if (!namesForCarousels.ContainsKey(name))
{
You might find it easier to follow your code if you use more descriptive variable names. It's not entirely clear what you're trying to do, but I assume you want to re-use the same carousel number for a given "Max Pn" if you've already allocated it - at the moment, you populate that mapping but you don't use it, you are reliant on max pn being in order. I don't actually see why carousel number wouldn't reset, but if you tidy it up perhaps you have a better chance of seeing what is happening.
Also given your null reference exception from your other question, this protects against that - though it probably indicates another problem elsewhere in the population of your "lstMx".
public static void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string defaultCarouselName = enter.Text;
int[] columnPaddings = new int[] { 15, 15, 25, 15, 15 };
StringBuilder completedOutputBuilder = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
completedOutputBuilder.AppendLine("Location".PadRight(15));
completedOutputBuilder.AppendLine();
int carouselNumberForEntry = 0;
Dictionary<string, int> maxPnToCarouselNumber = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
completedOutputBuilder.Append(_textfile[i].Cells[c].Replace(" ", "_").PadRight(columnPaddings[c]));
string maxPnForEntry = textfile[i].Cells[1];
int previouslyAllocatedCarouselNumberForMaxPn = 0;
if (maxPnToCarouselNumber.TryGetValue(maxPnForEntry, out previouslyAllocatedCarouselNumberForMaxPn) == false)
{
// assign a new courousel number for this max pn
carouselNumberForEntry++;
if (carouselNumberForEntry > 45)
carouselNumberForEntry = 1;
// for better clarity use add
maxPnToCarouselNumber.Add(maxPnForEntry, carouselNumberForEntry);
}
else
{
// use the carousel number previous assigned for this maxPn
carouselNumberForEntry = previouslyAllocatedCarouselNumberForMaxPn;
}
// find the related max pn carousel entry (if relatedPn is not found this suggests a problem elsewhere)
MAX_PN_Carousel relatedPn = lstMx.Find(x => x.MAX_PN != null && x.MAX_PN.Equals(maxPnForEntry, StringComparison.OrdinalIgnoreCase));
// assign the name from the entry, or use the default carousel name if unavailable
string carouselNameForMaxPn = (relatedPn == null || String.IsNullOrWhiteSpace(relatedPn.Carousel)) ? defaultCarouselName : relatedPn.Carousel;
// add the new column in the output
completedOutputBuilder.Append(String.Format("{0}:{1}", carouselNameForMaxPn, carouselNumberForEntry).PadRight(15));
completedOutputBuilder.Append("\r\n");
}
System.IO.File.WriteAllText(#"c:\dev\output.TXT", completedOutputBuilder.ToString());
}

Put multiple values in an array

I have a issue that i cant solve.
Here is the code
sik input = new sik();
for (int i = 0; i < 5; i ++)
{
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
}
sik[] inputs = new sik[]
{
input
};
Now i know this will only put 1 value in the sik[] list.
How can i put all the 5 values in this list.
Thanks
Note: i cannot initialize ski[] first. This has to be done in that order.
Any reason that it has to be an array?
List<sik> input = new List<sik>();
for (int i = 0; i < 5; i ++)
{
var newInput = new sik();
newInput.skId = securitiesArray[i].skId;
newInput.country = securitiesArray[i].country;
input.Add(newInput);
}
The reason that the List is useful is that it can dynamically grow with you, so you have no need to worry about how many instances you may need to add.
MSDN Documentation for List and all of it's glorious methods
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
sik[] inputs = new sik[5];
for (int i = 0; i < 5; i ++)
{
sik input = new sik();
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
inputs[i] = input;
}
You can use Linq to do this.
sik[] inputs = securitiesArray.Select(item =>
new sik()
{
skId = item.skId,
country = item.country
}).ToArray();
You can't have variable size array, instead you can use List.
List<sik> siks = new List<sik>();
sik input = new sik();
for (int i = 0; i < 5; i ++)
{
input.skId = securitiesArray[i].skId;
input.country = securitiesArray[i].country;
siks.Add(input);
}
If you want array yet, use sik[] inputs = skis.ToArray();
You can also do this,
List<sik> input=new List<sik>();
for(int i=0;i<securitiesArray.Length;i++)
{
input.Add(new{skId=securitiesArray[i].skid,country=securitiesArray[i].country});
}
For what it's worth, here the Linq approach:
sik[] inputs = Enumerable.Range(0, 5)
.Select(i => new sik{ kId = securitiesArray[i].skId, country = securitiesArray[i].country})
.ToArray();
If securitiesArray is of type sik(the properties suggest), you can select directly from it:
sik[] inputs = securitiesArray.Take(5).ToArray();

How do i check if the List length is bigger than the last time?

I have this code:
int LRLength = LR.Count;
for (int i = 0; i < LR.Count; i++)
{
LRLength = LR.Count;
LR = merge(LR);
if (LR.Count < LRLength)
{
LR = merge(LR);
if (LR.Count == LRLength)
{
break;
}
}
}
And this is the function merge:
private List<Lightnings_Extractor.Lightnings_Region> merge(List<Lightnings_Extractor.Lightnings_Region> Merged)
{
List<Lightnings_Extractor.Lightnings_Region> NewMerged = new List<Lightnings_Extractor.Lightnings_Region>();
Lightnings_Extractor.Lightnings_Region reg;
int dealtWith = -1;
for (int i = 0; i < Merged.Count; i++)
{
if (i != dealtWith)
{
reg = new Lightnings_Extractor.Lightnings_Region();
if (i < Merged.Count - 1)
{
if (Merged[i].end + 1 >= Merged[i + 1].start)
{
reg.start = Merged[i].start;
reg.end = Merged[i + 1].end;
NewMerged.Add(reg);
dealtWith = i + 1;
}
else
{
reg.start = Merged[i].start;
reg.end = Merged[i].end;
NewMerged.Add(reg);
}
}
else
{
reg.start = Merged[i].start;
reg.end = Merged[i].end;
NewMerged.Add(reg);
}
}
}
return NewMerged;
}
In this class: Lightnings_Extractor.Lightnings_Region I have only two int variables.
The idea in this function is to get a List and merge areas that are congruent.
For example once im calling the function and the List LR Length is 8 now I will get it back less. For example if it needed to merge two indexs to one then the List I will get in return the Length will be 7. If it will need to merge another indexs then the Length will be 6 and so on.
What I want to check on the first code above is when I should stop calling the function to merge indexs.
If the length was 8 and the next time it's still 8 do nothing stop the loop.
If the length is 8 and the next time it's 7 then call the function again.
If the length is 7 stop the loop . But if the length is 6 keep calling it once again.
Untill the last length will be the same as the length before !!!
So I tried this code but it's not working good:
int LRLength = LR.Count;
for (int i = 0; i < LR.Count; i++)
{
LRLength = LR.Count;
LR = merge(LR);
if (LR.Count < LRLength)
{
LR = merge(LR);
if (LR.Count == LRLength)
{
break;
}
}
}
Trying to make some assumptions as to what you're trying to accomplish. The following will basically capture the original length of the list for comparison. It will run at least once, and keep running until the LRLength == LR.Count
int LRLength = LR.Count;
do{
LR = merge(LR);
} while(LR.Count != LRLength);
If you were trying to run the loop until you got the same count twice in a row:
int prevCount;
do{
prevCount = LR.Count;
LR = merge(LR);
} while(prevCount != LR.Count);

Categories

Resources