C# - Console.ReadLine()与循环和字符串的奇怪交互

时间:2017-11-07 19:04:07

标签: c# random passwords

我在控制台应用程序中用C#编程了这个。

所以我想创建一个随机密码生成器,我基本上成功了,但是,我遇到了一个我无法理解的错误。

只打印1个密码不是问题。但是,当我想一次打印多个密码时,例如一个运行直到达到15的for循环,所有打印的密码都是相同的。但是,当我在for循环中编写Console.ReadLine()以基本上手动继续for循环时,打印另一个密码之后的密码并且它们都是不同的。

完整的代码就在那里。我感谢任何帮助。

static void Main(string[] args)
{
    for (int i = 0; i < 15; i++)
    {
        char[] alphabetUpper = GenerateCharacters(65, 91);
        char[] alphabetLower = GenerateCharacters(98, 124);
        int[] numbers = GenerateNumbers(47, 57);
        char[] specialCharacters = GenerateCharacters(34, 40);
        string password = CreatePassword(alphabetUpper, alphabetLower, specialCharacters, numbers);
        Console.WriteLine(password);
    }
    // Here I encounter the described problem. When I put the Console.ReadLine() in the for loop, it works normally though.
    Console.ReadLine();
}

// Generates characters with the numbers from the GenerateNumbers method by casting them.
static char[] GenerateCharacters(int lowerBorder, int upperBorder)
{
    int[] numberArray = GenerateNumbers(lowerBorder, upperBorder);
    char[] charArray = new char[100];
    for (int i = 0; i < numberArray.Length; i++)
    {
        charArray[i] = (char)numberArray[i];
    }
    return charArray;
}

// Upper and lower border of the numbers to ensure, that when the numbers are needed for characters, that only the wanted characters will be cast.
static int[] GenerateNumbers(int lowerBorder, int upperBorder)
{
    Random rng = new Random();
    int[] numberArray = new int[100];
    for (int i = 0; i < 98; i++)
    {
        int number = rng.Next(lowerBorder, upperBorder);
        numberArray[i] = number;
    }
    return numberArray;
}

static string CreatePassword(char[] alphabetUpper, char[] specialCharacters, char[] alphabetLower, int[] randomNumbers)
{
    var rng = new Random();
    int passwordLength = rng.Next(3, alphabetUpper.Length);
    var passwordCharacters = new char[passwordLength];
    var password = string.Empty;

    for (int i = 0; i < passwordLength; i++)
    {
        int whichArray = rng.Next(0, 4);
        int randomIndex = rng.Next(0, 100);

        if (whichArray == 0)
        {
            passwordCharacters[i] = alphabetUpper[randomIndex];
        }
        else if (whichArray == 1)
        {
            passwordCharacters[i] = specialCharacters[randomIndex];
        }
        else if (whichArray == 2)
        {
            passwordCharacters[i] = alphabetLower[randomIndex];
        }
        else
        {
            passwordCharacters[i] = (char)randomNumbers[randomIndex];
        }
    }

    for (int i = 0; i < passwordCharacters.Length; i++)
    {
        password += passwordCharacters[i];
    }

    return password;
}

0 个答案:

没有答案