Create a Visual C# application that displays the contents of the Teams.txt file
ID: 3602205 • Letter: C
Question
Create a Visual C# application that displays the contents of the Teams.txt file in a ListBox control. When the user selects a team in the ListBox, the application should display the number of times that team has won the World Series in the time period from 1903 to 2012. The two files used are Teams.txt , which contains a list of the names of teams that have won the Championship at least once, and WorldSeriesWinners.txt - this file contains a chronological list of the World Series winning teams from 1903 - 2012. The first line in the file is the nae of the team that won in 1903 and the last line is the name of the team that won in 2012.Note that the World Series was not played in 1904 or 1994.
Tip: Read the contents of the WorldSeriesWinners.txt file into a List or an array. When the user selects a team, an algorithm should step through the list or array counting the number of times the selected team appears. (for the purpose of this answer/code, the contents of the text files do not really matter, as long as the code works. The first part involving the Teams.txt is working but the second part of the code is not working, that is, the WorldSeriesWinner.txt part. The following part is the code that is not working. I'm getting error for this part if (lst_teams.SelectedIndex! = -1) . I hope you find the correct code that must quite ressemble this one. Thank you for your help!
private void GetTeamWin()
{
try
{
string selectedTeam; // Variable to hold selected team name
// Open the WorldSeriesWinners.txt file.
StreamReader inputWinner = File.OpenText("WorldSeriesWinners.txt");
// Create the List object to hold strings.
List winnerList = new List();
// Read the file's contents
while (!inputWinner.EndOfStream)
{
// Read a line and add it to the List
winnerList.Add(inputWinner.ReadLine());
}
// Close the file
inputWinner.Close();
if (lst_teams.SelectedIndex! = -1)
{
// Get the selected item.
selectedTeam = lst_teams.SelectedItem.ToString();
}
selectedTeam = lst_teams.SelectedItem.ToString();
var count = File.ReadLines("WorldSeriesWinners").Count(x => x.Contains(selectedTeam));
if (count > 0)
{
// Display the number of times the team has won.
lbl_Results.Text = " The " + selectedTeam + " has won the World Series" +
count + " time(s), between 1903 and 2012.";
}
else
{
// Display a message showing the team never won.
lbl_Results.Text = "The " + selectedTeam + " has never won the World Series.";
}
// Clear the List.
winnerList.Clear();
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
Explanation / Answer
what you wrote is
(lst_teams.SelectedIndex! = -1)
it needs to be
(lst_teams.SelectedIndex != -1)
there should be a space after variable and ! operator, else c# will throw