【问题标题】:How can I pick a random string from a list and assign it to a variable C#如何从列表中选择随机字符串并将其分配给变量 C#
【发布时间】:2016-02-12 02:38:53
【问题描述】:

我正在尝试制作一个程序,其中用户输入一个字符串,然后将该字符串存储在一个名为 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中,将label设置为flashCards1的返回值:

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

        label1.Text = class1.flashCards1();

    }

这也在Form1.cs中,并将文本保存到List:

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

        word1.Add(textBox1.Text);

        main.SetList1(word1);
    }

当我运行这段代码时,它给出了我的错误:

System.ArgumentOutOfRangeException 未处理 H结果=-2146233086 Message='maxValue' 必须大于零。 参数名称:maxValue 参数名称=最大值 源=mscorlib 堆栈跟踪: 在 System.Random.Next(Int32 最大值) 在 C:\Users\lottes\Source\Workspaces\Workspace\WindowsFormsApplication1\WindowsFormsApplication1\Class1.cs:line 19 中的 WindowsFormsApplication1.Class1.flashCards1() 在 C:\Users\lottes\Source\Workspaces\Workspace\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs: 中的 WindowsFormsApplication1.Form1.go_Click(Object sender, EventArgs e):第 62 行 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs 事件) 在 System.Windows.Forms.Control.WmMouseUp(消息和 m,MouseButtons 按钮,Int32 点击) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.ButtonBase.WndProc(消息和 m) 在 System.Windows.Forms.Button.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(味精和味精) 在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 原因,Int32 pvLoopData) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.Run(窗体 mainForm) 在 C:\Users\lottes\Source\Workspaces\Workspace\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19 中的 WindowsFormsApplication1.Program.Main() 在 System.AppDomain._nExecuteAssembly(RuntimeAssembly 程序集,字符串 [] 参数) 在 System.AppDomain.ExecuteAssembly(字符串 assemblyFile,证据 assemblySecurity,String [] args) 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在 System.Threading.ThreadHelper.ThreadStart_Context(对象状态) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback 回调,对象状态,布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态,布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态) 在 System.Threading.ThreadHelper.ThreadStart() 内部异常:

我尝试输入很多值,但似乎不起作用。我还看了这个帖子: How could I get a random string from a list and assign it to a variable

但是他们的解决方案给了我同样的错误。 任何帮助将不胜感激。对不起,如果这是太多/太少的信息。我试着讲道理。

【问题讨论】:

  • 您发布的代码甚至无法编译,更不用说显示运行时错误了。您必须将您的问题简化为Minimal Complete and Verifiable example 并发布。此外,包括完整的错误消息,包括堆栈跟踪。不要只从错误信息中挑选几个词;每个词都意味着什么。例如,“'maxValue' 必须大于零”可能意味着您有一个名为 maxValue 的变量,但您尚未向我们展示您尚未初始化。
  • 是的,我知道,我没有给出所有的代码,因为它是相当多的,因为我正在练习不同的课程。感谢您的反馈。
  • 我也没有看到异常的复制到剪贴板选项,所以我只是复制了我认为应该拥有的内容。我更新了帖子

标签: c# .net list random


【解决方案1】:

您的问题在于Random.Next(int) 方法。当您尝试使用负值作为最大参数时会出现此异常。这是因为它返回一个介于&gt;= 0 and &lt; maxValue 之间的值。哪个被负值弄乱了(当列表有 0 个项目时,在你的情况下为 -1)

修复很简单,只需更改:

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

进入:

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

这应该可行,因为 random 总是返回一个 小于最大值的值,所以应该访问 0 到 N - 1,其中 N 是列表的大小。

在此之后您将遇到更多问题(与此直接问题的相关性较小),因为核心问题是您尚未在 flashcards1() 函数中使用它之前初始化列表并添加值。在您向我们展示的示例中,尚不清楚如何解决该问题,但我建议您查看函数的执行顺序。

【讨论】:

  • 啊,好吧。谢谢你。我会看看它的运行顺序:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 2021-05-06
  • 2013-05-09
  • 1970-01-01
相关资源
最近更新 更多