简体   繁体   English

如何从列表中选择随机字符串并将其分配给变量C#

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

I am trying to make a program where the user enters a string and the string is then stored in a List named word1. 我正在尝试制作一个程序,用户在其中输入一个字符串,然后将该字符串存储在名为word1的列表中。 I want to pick a random string from the List, and display it in a label. 我想从列表中选择一个随机字符串,并将其显示在标签中。 I'm trying to do this using multiple methods and classes as practice. 我正在尝试使用多种方法和类来实现此目的。 Here's my code: 这是我的代码:

This is in the class Class1.cs: 这是在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;
    }

This one is in main.cs (not Main) and it talks to Class1. 这是在main.cs(不是Main)中,它与Class1对话。 Like I said this part is probably unnecessary but I was trying to practice with multiple methods. 就像我说的那样,这部分可能是不必要的,但我尝试使用多种方法进行练习。

    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;
    }

This one is in Form1.cs and sets the label to the return value of flashCards1: 这是在Form1.cs中,并将标签设置为flashCards1的返回值:

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

        label1.Text = class1.flashCards1();

    }

This is also in Form1.cs and saves the text to the List: 这也位于Form1.cs中,并将文本保存到列表中:

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

        word1.Add(textBox1.Text);

        main.SetList1(word1);
    }

When I run this code it gives my the error: 当我运行此代码时,它给了我错误:

System.ArgumentOutOfRangeException was unhandled HResult=-2146233086 Message='maxValue' must be greater than zero. 未处理System.ArgumentOutOfRangeException HResult = -2146233086消息='maxValue'必须大于零。 Parameter name: maxValue ParamName=maxValue Source=mscorlib StackTrace: at System.Random.Next(Int32 maxValue) at WindowsFormsApplication1.Class1.flashCards1() in C:\\Users\\lottes\\Source\\Workspaces\\Workspace\\WindowsFormsApplication1\\WindowsFormsApplication1\\Class1.cs:line 19 at WindowsFormsApplication1.Form1.go_Click(Object sender, EventArgs e) in C:\\Users\\lottes\\Source\\Workspaces\\Workspace\\WindowsFormsApplication1\\WindowsFormsApplication1\\Form1.cs:line 62 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow 参数名称: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) .WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at WindowsFormsApplication1.Program.Main() in C:\\Users\\lottes\\Source\\Workspaces\\Workspace\\WindowsFormsApplication1\\WindowsFormsApplication1\\Program.cs:line 19 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) a 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) t Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: 在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:

I've tried to enter lots of values but it doesn't seem to work. 我尝试输入很多值,但似乎不起作用。 I also looked at this thread: How could I get a random string from a list and assign it to a variable 我还查看了该线程: 如何从列表中获取随机字符串并将其分配给变量

However their solutions gave me the same error. 但是他们的解决方案给了我同样的错误。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Sorry if this was too much/little information. 很抱歉,如果这是太多/小信息。 I tried to make sense. 我试图说得通。

Your problem is with the Random.Next(int) method. 您的问题出在Random.Next(int)方法上。 This exception comes up when you try use a negative value as your maximum parameter. 当您尝试使用负值作为最大参数时,会出现此异常。 This is because it returns a value between >= 0 and < maxValue . 这是因为它返回的值在>= 0 and < maxValue Which gets messed up by negative values (-1 in your case when the list has 0 items) 哪个被负值搞乱了(如果列表中有0个项目,则为-1)

The fix is easy, just change : 修复很容易,只需更改即可:

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

into: 成:

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

This should work because random always returns a value less than the maximum value, so should access 0 through N - 1, where N is the size of your list. 这应该起作用,因为random总是返回小于最大值的值,因此应该通过N-1访问0,其中N是列表的大小。

You're going to have further problems after that one (and less related to this direct question) though because the core issue is that you haven't initialized your list and added values before using it in the flashcards1() function. 在此之后,您将遇到更多问题(与该直接问题不太相关),因为核心问题是在flashcards1()函数中使用该列表之前尚未初始化列表并添加值。 It's not clear how to solve that in the examples you've shown us, but I'd suggest looking at the order in which your functions execute. 在您展示给我们的示例中,如何解决该问题尚不清楚,但我建议您查看一下函数执行的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM