我想创建一个程序,当我单击按钮时,它会在消息框中显示一个随机类别(来自我创建的类别列表)和正确的单词。
当我运行它时,类别是随机的,但是应该与类别一起使用的正确单词没有正确放置。 错误图像
另外,我知道一旦程序达到某个类别的负索引或显示所有类别时,程序将 崩溃
但我无法弄清楚要使用什么逻辑,以便一旦达到负值它就会自动停止删除索引。
代码:
namespace randomCategory
{
public partial class Form1 : Form
{
Random rand = new Random();
List<string> categories = new List<string> { "Book Titles", "Movie Titles", "Car Parts", "Human Body Parts", "Transportations" };
public Form1()
{
InitializeComponent();
listBox1.DataSource = categories;
}
public void selection()
{
// logic for setting a random category
int index = rand.Next(categories.Count);
var category = categories[index];
// logic for assigning the word for a category
switch (index)
{
case 0:
MessageBox.Show(category, "Harry Potter");
break;
case 1:
MessageBox.Show(category, "Summer Wars");
break;
case 2:
MessageBox.Show(category, "Bumper");
break;
case 3:
MessageBox.Show(category, "Eyes");
break;
case 4:
MessageBox.Show(category, "Boat");
break;
default:
MessageBox.Show("Empty!", "!!!");
break;
}
categories.RemoveAt(index);
}
private void button1_Click(object sender, EventArgs e)
{
selection();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}