C#ListBox数组故障



全部。我正在创建一个程序,该程序将团队列表作为字符串阵列列表,并将其比较它,其中包含所有世界赛冠军列表的.txt文件,并确定一个团队赢得了多少次赢得了世界系列赛的赢得了世界大赛,以此为基础。在列表框中选择。

我的代码是丢弃0个错误,我第一次运行了程序并选择了一个团队,然后单击它显示的按钮显示了显示团队名称的消息框以及他们赢了多少次。之后,每当我再次选择一个团队并单击按钮时,什么也不会发生。它只是冻结。然后,我必须停止调试。可能会出错什么?有什么想法和建议吗?

namespace WorldSeriesWinners
{
    public partial class Form1 : Form
   {
        string[] inputTeams = 
        { 
          "Boston Americans", "New York Giants", "Chicago White Sox","Chicago Cubs",
          "Pittsburgh Pirates", "Philadelphia Athletics","Boston Red Sox", "Boston Braves",
          "Cincinatti Reds", "Cleveland Indians","Brooklyn Dodgers",
          "New York Yankees", "Washington Senators", 
          "St. Louis Cardinals","Detroit Tigers", "Milwaukee Braves",
          "Los Angeles Dodgers", "New York Mets", "Baltimore Orioles",
          "Oakland Athletics", "Philadelphia Phillies", "Kansas City Royals", "Minnesota Twins", "Toronto Blue Jays", 
          "Atlanta Braves", "Florida Marlins", "Arizona Diamondbacks", "Anaheim Angels", "San Francisco Giants"
        };
    string[] worldseriesWinners = new string[104];
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.AddRange(inputTeams);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        StreamReader champFile = File.OpenText("WorldSeriesWinners.txt");
        List<string> inputTeams = new List<string>();
        string selectedTeam;
        while (!champFile.EndOfStream)
        {
            inputTeams.Add(champFile.ReadLine());
        }
        while (listBox1.SelectedIndex != 0)
        {
            selectedTeam = listBox1.SelectedItem.ToString();
        }
        selectedTeam = listBox1.SelectedItem.ToString();
        var count = File.ReadLines("WorldSeriesWinners.txt").Count(x => x.Contains(selectedTeam));
        if (count > 0)
        {
            MessageBox.Show("The " + selectedTeam + "has won the World Series " + count + " times! ");
        }
        else
        {
            MessageBox.Show("The " + selectedTeam + "has never won the World Series.");
        }
    }
}

您的代码永远不会工作

while (listBox1.SelectedIndex != 0)
{
    selectedTeam = listBox1.SelectedItem.ToString();
}

将永远保持运行,因为如果您在第一个条目以外的ListBox中选择了任何其他项目,那么ListBox1.SelectedIndex将永远不会为0,并且它将永远循环。没有理由有一段时间循环阅读所选项目。

完成时需要关闭流

private void button2_Click(object sender, EventArgs e)
{
    StreamReader champFile = File.OpenText("WorldSeriesWinners.txt");
 ...
     champFile.Close();
} 

最佳实践是使用using语句

private void button2_Click(object sender, EventArgs e)
{
    using(StreamReader champFile = File.OpenText("WorldSeriesWinners.txt"))
    {
 ...
     }
} 

您可以通过将File.OpenText包装在try语句中来测试。并打破渔获。

尝试做这个

using(StreamReader champFile = File.OpenText("WorldSeriesWinners.txt")){
...
}

最新更新