In my code, I only ever return the last element and realize this is because it is overwriting the previous ones entered but have no idea how to fix this then determine the largest.
CodePudding user response:
You don't need an array to keep track of the one largest item, but you do need a check(when you're looping over your list) of whether the item you currently looking at is bigger than the previously known max
int.Parse won't tolerate the "MB" text being present when trying to parse an int; you'll need to remove it (Replace it with nothing) before you parse
- Change the
largestso it's anintinstead. A good starting value for a variable that holds a maximum, is the minimum possible value -int.MinValue - Use
Replace("MB","")to make your file size parseable - Parse the file size to an int
- Implement a logic of "if the parsed size is greater than the largest, set largest to be the parsed size"
CodePudding user response:
Caius Jard has exactly described the points you have to implement to make your code work as required.
Let me show you how I would do it using those points without using internal Max method.
private void AddSize_Click(object sender, EventArgs e)
{
listStorage.Items.Add(textBox1.Text "MB");
}
private void FindMax_Click(object sender, EventArgs e)
{
int ItemCount = listStorage.Items.Count;
int[] FileSize = new int[ItemCount];
for (int i = 0; i < ItemCount; i )
{
string TrimmedSize = ((string)listStorage.Items[i]).Replace("MB", "");
FileSize[i] = int.Parse(TrimmedSize);
}
int Max = FileSize[0];
for (int i = 1; i < ItemCount; i )
{
if (FileSize[i]>Max)
{
Max = FileSize[i];
}
}
MessageBox.Show($"{Max} MB is largest");
}
Note that I've used MessageBox instead of writing the message inside the listbox since it doesn't make any sense overwriting your data that you might want to refer later.
