我想創建一個程序,當我單擊按鈕時,在消息框中使用正確的單詞顯示一個隨機類別(來自我創建的類別列表)。在列表C中隨機化字符串時出錯#
當我運行它時,這些類別是隨機的,但是應該與類別對應的正確單詞沒有正確放置。 Image of Error
而且,我知道,一旦程序到達類別的負指數或一旦所有類別的程序會崩潰顯示 Image of Error
,但我想不出用什麼邏輯所以它會自動停止刪除索引,一旦它達到了負值。
代碼:
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)
{
}
}
}
你有沒有想過改變'列表'爲使用'HashSet的,LinkedList的或Dictionary' –
MethodMan
@DJKRAZE我有點新的C#,現在試圖尋找如何使用字典,因爲它也推薦其他人說的方式。我想着如何將代碼轉換成HashSet和LinkedList的方法。 – Coolai
我發佈了一個簡單的例子,關於如何將現有的列表轉換爲字典 –
MethodMan