Removing entries from a 2-Dimensional Array - c#

I'm doing a university assignment and I'm having some trouble with my Array.
I am building a console based address book application and I need to use a 2D-Array which has the options of adding, removing, or printing the contents of the Array...
I am deleting the current entries by replacing the values with "XXX" -as is required in the brief. I then just hide the "XXX" values when printing to screen.
But once I have 'Deleted' an entry, when it comes to printing the entire Array, anything listed AFTER the entry I tried to delete, does not show up at all, except after adding a new entry.
Could anyone shed some light on why this may be happening?

In your code you're deleting the whole column, once the if statement catch a true condition, e.g. if the address[1, 1] == DeleteName then your array after the for loop will look like:
A00 XXX A02 ...
A10 XXX A13 ...
A20 XXX A23 ...
A30 XXX A33 ...
... ...
So if you just need to delete an entry you will need two loops like this:
for (int i = 0; i < 5; i++)
{
for(int j =0;j < 5; j++)
{
if (Address[i, j] == DeleteName)
{
Address[i, j] = "XXX";
Console.WriteLine("Contact Deleted");
}
}
}

Also, in your case 3 it looks like you're missing the { } after your else statement
else
{
FName = Address[i, 0];
LName = Address[i, 1];
Number = Address[i, 2];
Road = Address[i, 3];
Town = Address[i, 4];
Console.WriteLine(LName +", " + FName + " - "+ Number + ", " + Road+", " + Town);
}

Related

Minitab Automation and Skipping Columns

My main code is below:
Mtb.Application MtbApp = new Mtb.Application();
MtbApp.UserInterface.Visible = true;
MtbApp.UserInterface.DisplayAlerts = false;
Mtb.Project MtbProj = MtbApp.ActiveProject;
Mtb.Columns MtbColumns;
Mtb.Column MtbColumn1;
Double[] data1;
Hashtable htSingleColumn;
List<double> listSingleColumn;
int i = 1 ;
foreach (DictionaryEntry de in htDataTable)
{
htSingleColumn = (Hashtable)de.Value;
listSingleColumn = (List<double>)htSingleColumn["listSingleData"];
data1 = listSingleColumn.ToArray();
MtbColumns = MtbProj.ActiveWorksheet.Columns;
MtbColumn1 = MtbColumns.Add(null, null, i);
MtbColumn1.SetData(data1);
// strLowlim and strUpplim have no influence on this issue here
strCommand = "Capa C" + i+" 1;" + ((strLowlim == "NA") ? "" : (" Lspec " + strLowlim + ";")) +((strUpplim == "NA") ? "" : (" Uspec " + strUpplim + ";"))+ " Pooled; AMR; UnBiased; OBiased; Toler 6; Within; Percent; CStat.";
// The program is crashing here as a result of the columns not being created sequentially
MtbProj.ExecuteCommand(strCommand);
Mtb.Graph MtbGraph = MtbProj.Commands.Item(i).Outputs.Item(1).Graph;
MtbGraph.SaveAs("C:\\MyGraph" + DateTime.Now.ToString("yyyy-MM-dd HHmmss"), true, Mtb.MtbGraphFileTypes.GFPNGHighColor);
i++;
}
MtbApp.Quit();
When running this code (with the crashing section commented out), I get the following output:
It should look like this:
I am really puzzled about this result. The variable i is right, but what is affecting the column number?
I can't find much information on the Web about Minitab. I just read the start guide here.
This line is the problem.
MtbColumn1 = MtbColumns.Add(null, null, i);
The third parameter Quantity specifies the number of columns to add. On the first iteration of the loop, you add i = 1 column, but on the second iteration of the loop you add i = 2 columns. Each iteration of the loop will add an additional i columns, when what you really want is to add one column each time.
Change the line to:
MtbColumn1 = MtbColumns.Add();

Splitting String from Settings

I'm trying to read out the contents off a Setting inside my Application. Below is the code i'm having troubles with:
private bool checkGrid()
{
string playlists = Spotify_Extender.Properties.Settings.Default.Playlists;
MessageBox.Show(playlists);
string[] split1;
if (playlists.Contains(";"))
{
MessageBox.Show("Multiple Links");
split1 = playlists.Split(';');
}
else
{
MessageBox.Show("One Link");
split1 = new string[1];
split1[0] = playlists;
}
MessageBox.Show("Array Length: " + split1.Length);
int lines = 0;
for (int i = 0; i < split1.Length; i++)
{
MessageBox.Show("Check #" + i + " - " + split1[i] + " - Length: " + split1[i].Length);
if (split1[i].Length >= 22)
{
MessageBox.Show(i + " - " + split1[1]);
lines++;
}
}
int rows = this.playlistGrid.Rows.Count;
MessageBox.Show(lines + "");
if (rows == lines)
return true;
return false;
}
The code should be easy to understand and it should work as far as i am aware, but it doesn't. I entered this in my Setting:
If i run the program now, my first MessageBox prints out exactly what i entered, the second one prints out "One Link" and the third prints "Array Length: 1". Now we get to the part i'm having troubles with. The next Message is this:
So the length of the text is 22 as displayed in the MessageBox, but down below this statement isn't true:
if (split1[i].Length >= 22)
I'm really confused by this and it also does this when i check this:
if (split1[i] != "")
Any help is appreciated, because i don't know what to do, since my code should be fine. Thanks for your time!
You should have split[i] and not split[1]

Alternating row-column headers in worksheet with EPPlus

I am trying to print output from a custom structure into Excel file. What I am trying to do is:
COLUMN NAME
PLAYER
PLAYER
COLUMN NAME
PLAYER
PLAYER
But What I am getting is
COLUMN NAME
COLUMN NAME
PLAYER
PLAYER
CODE:
int i = 1;
foreach (var item in scoresheet.Positions)
{
var column = wb.Cells;
if ((i % 5) == 1)
{
column["A" + i].LoadFromText("Initial Rank");
}
else
{
column["A" + i + 1].LoadFromText(item.Player.FirstName);
}
i++;
}
Looking at your line:
column["A" + i + 1].LoadFromText(item.Player.FirstName);
I assume you want that to be, say, a result of "A2" when i is equal to 1. BUT, what you will actually end up with is "A11" since it will do it as a string concatenation. What you need is:
column["A" + (i + 1)].LoadFromText(item.Player.FirstName);

Confusing indexing error while going line by line through some text

I'm reading in some text, line by line, and I'd like to tokenize the words and create 1-grams and 2-grams, but I think there's a problem with my indexing because I either get an index error or it'll say that the item I'm trying to modify in my dictionary doesn't exist, which is totally weird, since I wrote the code to first make the dictionary item and if it already exists, to increment a counter.
Basically, my dictionaries are of the form (n-gram string, frequency int)
System.IO.StreamReader lines = new System.IO.StreamReader("myfile");
while (true)
{
string line = lines.ReadLine().ToLower();
if (line == null) break;
if (line.Trim().Length == 0) continue;
string[] tokens = Regex.Split(line, "[^\\w']+");
for (int i = 0; i < tokens.Count()-1; i++)
{
try
{
one_gram.Add(tokens[i], 1);
two_gram.Add(tokens[i] + " " + tokens[i + 1], 1);
}
catch
{
one_gram[tokens[i]]++;
two_gram[tokens[i] + " "+tokens[i + 1]]++;
}
}
}
Can anyone look at my code and tell me where I went wrong? The problem seems to occur at the end of the for loop at the first line, but if I do
for(int i=0;i<tokens.Count()-3;i++)
then the error happens in the second line... but I'm not sure exactly what's causing it.
EDIT: As per suggestions, I tried using the ContainsKey method, but I still get an error near the end of the first line saying that I'm adding a Key that already exists, even though the if statements are supposed to catch that?!
for (int i = 0; i < tokens.Count()-1; i++)
{
if (one_gram.ContainsKey(tokens[i]))
{
one_gram[tokens[i]]++;
}
if (two_gram.ContainsKey(tokens[i] + " " + tokens[i + 1]))
{
two_gram[tokens[i] + " " + tokens[i + 1]]++;
}
one_gram.Add(tokens[i], 1);
two_gram.Add(tokens[i] + " " + tokens[i + 1], 1);
}
You need to use an else (or break):
for (int i = 0; i < tokens.Count() - 1; i++)
{
// Save yourself typing errors by creating variables to hold
// the key values and then you can just use the variable name
var oneGramKey = tokens[i];
var twoGramKey = string.Format("{0} {1}", tokens[i], tokens[i + 1]);
if (one_gram.ContainsKey(oneGramKey))
{
one_gram[oneGramKey]++;
}
else
{
one_gram.Add(oneGramKey, 1);
}
if (two_gram.ContainsKey(twoGramKey))
{
two_gram[twoGramKey]++;
}
else
{
two_gram.Add(twoGramKey, 1);
}
}

Data lost while adding string to listbox

I am cycling through the contents of a two-dimensional array containing the result of a Punnett Square calculation for gene crosses. I need to summarize the result so that the user can readily see the unique instances. I can accomplish this by putting the result into a text box, but when I try and use a ListBox to display the data, part of the information is getting lost, namely a translation of the AaBBCc type data to something that directly relates to the traits that the user initially selected.
This is the main block of code for the operation:
foreach (string strCombination in arrUniqueCombinations)
{
int intUniqueCount = 0;
decimal decPercentage;
foreach (string strCrossResult in arrPunnettSQ)
{
if (strCrossResult == strCombination)
{
intUniqueCount++;
}
}
decPercentage = Convert.ToDecimal((intUniqueCount*100)) / Convert.ToDecimal(intPossibleCombinations);
txtReport.AppendText(strCombination + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%."+ Environment.NewLine);
lstCrossResult.Items.Add(DecodeGenome(strCombination) + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%.");
}
For appending the data to the textbox I use this code and it works perfectly:
txtReport.AppendText(DecodeGenome(strCombination) + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%."+ Environment.NewLine);
Giving the result:
Trait 1 Het.,Trait 3 appears 16 times or 25%.
For adding the result to a list box, this works:
lstCrossResult.Items.Add(strCombination + " appears " + intUniqueCount.ToString() + " times or " + decPercentage.ToString() + "%.");
Giving the result:
AaBBCc appears 16 times or 25%.
But the contents of strCombination is AaBBCc and I need it translated to "Trait 1 Het.,Trait 3", which I accomplish with this bit of code:
private string DecodeGenome(string strGenome)
{
string strTranslation = "";
int intLength = strGenome.Length;
int intCounter = intLength / 2;
string[] arrPairs = new string[intLength / 2];
//Break out trait pairs and load into array
for (int i = 1; i <= intLength; i++)
{
arrPairs[i / 2] = strGenome.Substring((i-1),2);
i++;
}
foreach (string strPair in arrPairs)
{
char chFirstLetter = strPair[0];
char chSecondLetter = strPair[1];
intCounter = intCounter - 1;
if (Char.IsUpper(chFirstLetter))
{
if (!Char.IsUpper(chSecondLetter))
{
if (intCounter > 0)
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)) + " Het.,");
}
else
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)));
}
}
}
else
{
if (!Char.IsUpper(chSecondLetter))
{
if (intCounter > 0)
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)) + ",");
}
else
{
txtReport.AppendText(GetDescription(strPair.Substring(0, 1)));
}
}
}
}
return strTranslation;
}
That has no problem displaying in a text box, but when I try and put it as an item into a list box it turns it into null. Instead of:
"Trait 1 Het.,Trait 3 appears 16 times or 25%."
I get:
" appears 16 times or 25%."
I have tried adding the results to an ArrayList, then populating the listbox after everything is processed, but the result is the same.
Any clues as to why the list box is not accepting the translated AaBBCc information would be greatly appreciated.
strTranslation is never set. Everything is pushed to txtReport.AppendText

Categories

Resources