Question

In: Computer Science

In C Sharp with the use of the Try and Catch method create an application that...

In C Sharp with the use of the Try and Catch method create an 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 the team has won the World Series in the time period from 1903 through 2012.

Teams.txt--This file contains a list of several Major League baseball teams in alphabetical order. Each team listed in the file has won the World Series at least once.

WorldSeriesWinners.txt - This file contains a chronological list of the World Series' winning teams from 1903 through 2012. (The first line in the file is the name 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.)

Hint: Read the contents of the WorldSeriesWinners.text file into a List. When the user selects a team in the ListBox, the application should display the number of times the selected team appears.

Solutions

Expert Solution

C-Sharp Windows Application:

File: Form1.Designer.cs

namespace worldChampionship
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbTeams = new System.Windows.Forms.ListBox();
this.lblHeading = new System.Windows.Forms.Label();
this.lblResult = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnCount = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.txtWins = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// lbTeams
//
this.lbTeams.FormattingEnabled = true;
this.lbTeams.Location = new System.Drawing.Point(349, 48);
this.lbTeams.Name = "lbTeams";
this.lbTeams.Size = new System.Drawing.Size(141, 186);
this.lbTeams.TabIndex = 0;
//
// lblHeading
//
this.lblHeading.AutoSize = true;
this.lblHeading.Font = new System.Drawing.Font("Modern No. 20", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblHeading.Location = new System.Drawing.Point(15, 9);
this.lblHeading.Name = "lblHeading";
this.lblHeading.Size = new System.Drawing.Size(292, 18);
this.lblHeading.TabIndex = 1;
this.lblHeading.Text = "Select a team to count number of wins";
//
// lblResult
//
this.lblResult.AutoSize = true;
this.lblResult.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblResult.Location = new System.Drawing.Point(14, 48);
this.lblResult.Name = "lblResult";
this.lblResult.Size = new System.Drawing.Size(118, 19);
this.lblResult.TabIndex = 2;
this.lblResult.Text = "Number of wins:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(345, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 19);
this.label1.TabIndex = 4;
this.label1.Text = "Teams";
//
// btnCount
//
this.btnCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCount.Location = new System.Drawing.Point(18, 134);
this.btnCount.Name = "btnCount";
this.btnCount.Size = new System.Drawing.Size(75, 23);
this.btnCount.TabIndex = 5;
this.btnCount.Text = "Count";
this.btnCount.UseVisualStyleBackColor = true;
this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
//
// btnExit
//
this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnExit.Location = new System.Drawing.Point(146, 134);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(75, 23);
this.btnExit.TabIndex = 6;
this.btnExit.Text = "Exit";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// txtWins
//
this.txtWins.Location = new System.Drawing.Point(32, 82);
this.txtWins.Name = "txtWins";
this.txtWins.Size = new System.Drawing.Size(100, 20);
this.txtWins.TabIndex = 7;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(502, 262);
this.Controls.Add(this.txtWins);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnCount);
this.Controls.Add(this.label1);
this.Controls.Add(this.lblResult);
this.Controls.Add(this.lblHeading);
this.Controls.Add(this.lbTeams);
this.Name = "Form1";
this.Text = "World Championship League";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.ListBox lbTeams;
private System.Windows.Forms.Label lblHeading;
private System.Windows.Forms.Label lblResult;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnCount;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.TextBox txtWins;
}
}

File: Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace worldChampionship
{
public partial class Form1 : Form
{
//List to hold winners data
List<string> winners = new List<string>();

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//Loading WorldSeriesWinners.txt file into list
loadWinnersFile();
  
//Opening file for reading
StreamReader sr = new StreamReader("Teams.txt");
string team = "";

try
{
//Reading team
team = sr.ReadLine();
  
//Read till end of file is reached
while (team != null)
{
this.lbTeams.Items.Add(team);
  
//Reading next team
team = sr.ReadLine();
}

//closing file
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//closing file
sr.Close();
}
}

/* Method that loads winners data from file into list */
public void loadWinnersFile()
{
//Opening file for reading
StreamReader sr = new StreamReader("WorldSeriesWinners.txt");
string team = "";

try
{
//Reading team
team = sr.ReadLine();

//Read till end of file is reached
while (team != null)
{
winners.Add(team);

//Reading next team
team = sr.ReadLine();
}

//closing file
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//closing file
sr.Close();
}
}


//Count button click event handler
private void btnCount_Click(object sender, EventArgs e)
{
string teamSelected;

//Getting the team selected
teamSelected = lbTeams.SelectedItem.ToString();

int won = 0;

//Iterating over winners list
for (int i = 0; i < winners.Count; i++)
{
//If team is found
if (winners[i].Equals(teamSelected))
{
//Incrementing number of wins
won = won + 1;
}
}

//Writing number of wins to label
txtWins.Text = won.ToString();
}

private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}


}
}

_______________________________________________________________________________________________

Sample Run:


Related Solutions

Create in C Sharp : Create an application that predicts the approximate size of a population...
Create in C Sharp : Create an application that predicts the approximate size of a population of organisms. The application should use text boxes to allow the user to enter the starting number of organisms, the average daily population increase (as a percentage), and the number of days the organisms will be left to multiply. For example, assume the user enters the following values in text boxes: Starting number of organisms: 2 Average daily increase: 30% Number of days to...
Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors...
Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors using System; using System.Collections.Generic;                    public class Program {    public static void Main()    {        List<int> list = new List<int>();               Console.WriteLine("Please input integers: (in one line)");                      string input = Console.ReadLine();        string[] tokens = input.Split(); // split string into tokens "12 13 10" -> "12" "13"...
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
Find the readData() method Inside this method is a try block without any catch statements. Add...
Find the readData() method Inside this method is a try block without any catch statements. Add the following 5 catch statements to this file (Hint: put them in the right order): RuntimeException Exception FileNotFoundException NumberFormatException InputMismatchException For each of these print out a short message describing the exception that occurred Java Class import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.Scanner; public class ReadInData {    public static double readData(String fileName) {        File file = new File(fileName);       ...
create your own function that wraps it with try catch. Pass in the string to parse,...
create your own function that wraps it with try catch. Pass in the string to parse, and the name of the field, put some logging in the catch How do I do this? say with this code segment? void readStudents() { //Scanner class object declare Scanner readStudentFile = null; //try block begin try { //open file readStudentFile = new Scanner(new File(".\\src\\test\\student.txt")); //loop until end of file while(readStudentFile.hasNextLine()) { String stu = readStudentFile.nextLine(); String[] eachStu; eachStu = stu.split(" "); students.add(new Student(eachStu[0],...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally...
A brief explanation is needed for these true/false questions. a) A method that contains a try-catch-finally structure may also have a “throws” declaration. b) An arithmetic exception such as division by zero can be avoided by careful programming while an I/O exception such as file not found may occur regardless of the precautions taken by the programmer. c) Lets assume that you create an object x of the Object class. You can assign any object (objects of other classes) to...
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
programming language is c#. Create a method that prompts a user of your console application to...
programming language is c#. Create a method that prompts a user of your console application to input the information for a student: static void GetStudentInfo() { Console.WriteLine("Enter the student's first name: "); string firstName = Console.ReadLine(); Console.WriteLine("Enter the student's last name"); string lastName = Console.ReadLine(); // Code to finish getting the rest of the student data ..... } static void PrintStudentDetails(string first, string last, string birthday) { Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday); } 1. Using the...
Create an C# application named ConvertMilesToKilometers whose Main() method prompts a user for a number of...
Create an C# application named ConvertMilesToKilometers whose Main() method prompts a user for a number of miles, passes the value to a method that converts the value to kilometers, and then returns the value to the Main() method where it is displayed.
Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass...
Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass and create three methods myMethod1(), Method2() and Method3(). Invoke Method2() from Method1() and Method3() from Method2(). Write a code that can throw an exception inside myMethod3() and compile: File file=new File("filename.txt"); Scanner sc=new Scanner(file); You will get compilation errors now, as you are not handling a checked exception FileNotFoundException. Declare throws over myMethod3() and myMethod2(). You will need to add throws FileNotFoundException on myMethod()...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT