【发布时间】:2020-12-15 14:59:39
【问题描述】:
我一直在尝试用字母数字字符创建一个随机字符串,并使用 Do-While 循环来检查随机字符串是否符合要求。否则,它应该继续执行循环。但是,我发现我总是一遍又一遍地生成相同的字符串的代码。为了演示,我设置了int message_length = 2 并要求While Loop 检查生成的字符串是否为“ab”,如while (check != "ab")。
我尝试将Random seed = new Random() 放在 Do 循环中,在 Do 循环之外,在 Main() 之外,你可以看到我注释掉的代码。他们都没有工作。我使用了 Visual Studio 2017、Windows 10 家庭版。任何人都可以帮忙吗?非常感谢!
(Further cmets: 虽然我现在的代码工作正常,但我仍然不明白为什么在这种情况下原行 check = all_message.ToString(); 可以中断随机数生成器。恕我直言,while 条件 while (check != "ab") 仍然是 True所以循环将继续进行。但是为什么随机数生成器停止生成新种子?任何人都可以分享这方面的知识吗?
using System;
using System.Text;
using System.Collections.Generic;
public class Program
{
//static Random seed = new Random();
public static void Main(string[] arggs)
{
Random seed = new Random();
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Console.WriteLine(src.Length);
int string_length = 2;
List<string> all_message = new List<string>();
string check = "";
do
{
//Random seed = new Random();
int i = 0;
StringBuilder message = new StringBuilder();
for (int j = 0; j < string_length; j++)
{
char c = src[seed.Next(0, src.Length)];
message.Append(c);
}
all_message.Add(message.ToString());
check = all_message.ToString();
Console.WriteLine(i + " = " + all_message[i]);
i++;
}
while (check != "ab");
}
}
【问题讨论】:
-
check = message.ToString();? TBH,目前还不清楚您要做什么。 -
感谢您的快速回复。
all_message的类型是StringBuilder。所以我需要check = message.ToString()将其转换为字符串类型。 -
@JohnnyMopp 不要混淆 OP -
all_message.ToString();- 不会“将列表转换为字符串”,而只是“返回列表类型的名称”......(显然永远不会是“ab ",但那是供 OP 调试的) -
2 件事:1.
check将 始终 为 'System.Collections.Generic.List1[System.String]' (yes, that string literally). I don't think it's doing what you think it's doing. 2. Why do you think your loop is generating the same string? Just put a breakpoint where you assignc` 并查看它是否改变。我敢打赌。 -
Use your debugger 看看
check是什么。这不是你想的那样。我们无能为力,因为我们不明白您要做什么。List<string>不可能等于ab。
标签: c# random while-loop do-while random-seed