簡體   English   中英

如何從列表中選擇隨機字符串並將其分配給變量C#

[英]How can I pick a random string from a list and assign it to a variable C#

我正在嘗試制作一個程序,用戶在其中輸入一個字符串,然后將該字符串存儲在名為word1的列表中。 我想從列表中選擇一個隨機字符串,並將其顯示在標簽中。 我正在嘗試使用多種方法和類來實現此目的。 這是我的代碼:

這是在Class1.cs類中:

    main main = new main();

    public string flashCards1()
    {
        List<string> word1 = main.GetList1();

        Random rnd = new Random();

        int rtn = rnd.Next(word1.Count - 1);

        string word = word1[rtn];

        string rtnWord = word.ToString();

        return rtnWord;
    }

這是在main.cs(不是Main)中,它與Class1對話。 就像我說的那樣,這部分可能是不必要的,但我嘗試使用多種方法進行練習。

    private List<string> word2 = new List<string>();
    private List<string> word1 = new List<string>();

    public List<string> GetList1()
    {
        return word1;
    }

    public void SetList1(List<string> updatedList)
    {
        word1 = updatedList;
    }

這是在Form1.cs中,並將標簽設置為flashCards1的返回值:

    private void go_Click(object sender, EventArgs e)
    {
        menu.Visible = false;
        cards.Visible = true;

        label1.Text = class1.flashCards1();

    }

這也位於Form1.cs中,並將文本保存到列表中:

    private void enter_Click(object sender, EventArgs e)
    {
        List<string> word1 = main.GetList1();

        word1.Add(textBox1.Text);

        main.SetList1(word1);
    }

當我運行此代碼時,它給了我錯誤:

未處理System.ArgumentOutOfRangeException HResult = -2146233086消息='maxValue'必須大於零。 參數名稱:maxValue ParamName = maxValue源= mscorlib StackTrace:位於C:\\ Users \\ lottes \\ Source \\ Workspaces \\ Workspace \\ WindowsFormsApplication1 \\ WindowsFormsApplication1 \\ Class1中WindowsFormsApplication1.Class1.flashCards1()的System.Random.Next(Int32 maxValue)處。 WindowsFormsApplication1.Form1.go_Click上的cs:line 19(Object sender,EventArgs e)位於C. \\ Users \\ lottes \\ Source \\ Workspaces \\ Workspace \\ WindowsFormsApplication1 \\ WindowsFormsApplication1 \\ Form1.cs:System.Windows.Forms.Control的62行。 System.Windows.Forms.Button.OnClick(EventArgs e)在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)處在System.Windows.Forms.Control.WmMouseUp(Message&m,MouseButtons button, Int32在System.Windows.Forms.ButtonBase.WndProc(Message&m)在System.Windows.Forms.ButtonBase.WndProc(Message&m)在System.Windows。 System.Windows.Forms.Control.ControlNativeWindow上的Forms.Control.ControlNativeWindow.OnMessage(Message&m) System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)的.WndProc(Message&m)在System.Windows.Forms的System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&msg)處。 Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32原因,Int32 pvLoopData)在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32原因,ApplicationContext上下文)在System.Windows.Forms C. \\ Users \\ lottes \\ Source \\ Workspaces \\ Workspace \\ WindowsFormsApplication1中System.Windows.Forms.Application.Run(Form mainForm)在WindowsFormsApplication1.Program.Main()處的.Application.ThreadContext.RunMessageLoop(Int32原因,ApplicationContext上下文) \\ WindowsFormsApplication1 \\ Program.cs:Line 19位於System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)位於System.AppDomain.ExecuteAssembly(String程序集,證據assemblySecurity,String [] args) 在System.Threading處的System.Threading.ThreadHelper.ThreadStart_Context(對象狀態)處的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在System.Threading.ExecutionContext.RunInternal(ExecutionContext執行上下文,ContextCallback回調,對象狀態,布爾狀態saveSyncCtx)處。 System.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回調,對象狀態)在System.Threading.ThreadHelper.ThreadStart()處的ExecutionContext.Run(ExecutionContext執行上下文,ContextCallback回調,對象狀態,布爾值saveSyncCtx)InnerException:

我嘗試輸入很多值,但似乎不起作用。 我還查看了該線程: 如何從列表中獲取隨機字符串並將其分配給變量

但是他們的解決方案給了我同樣的錯誤。 任何幫助將不勝感激。 很抱歉,如果這是太多/小信息。 我試圖說得通。

您的問題出在Random.Next(int)方法上。 當您嘗試使用負值作為最大參數時,會出現此異常。 這是因為它返回的值在>= 0 and < maxValue 哪個被負值搞亂了(如果列表中有0個項目,則為-1)

修復很容易,只需更改即可:

        int rtn = rnd.Next(word1.Count - 1);

成:

        int rtn = rnd.Next(word1.Count);

這應該起作用,因為random總是返回小於最大值的值,因此應該通過N-1訪問0,其中N是列表的大小。

在此之后,您將遇到更多問題(與該直接問題不太相關),因為核心問題是在flashcards1()函數中使用該列表之前尚未初始化列表並添加值。 在您展示給我們的示例中,如何解決該問題尚不清楚,但我建議您查看一下函數執行的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM