几天前我开始学习 C#,并认为随机密码生成器将是一个很好的入门项目。它仅适用于字母,但现在我还想包含数字和符号数组,它经常输出错误数量的字符,如本例所示:
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace randompassword
{
internal class Program
{
static void Main(string[] args)
{
// Variables
int pwlength;
string includeSym;
string includeNum;
// Dictionary
char[] symbols = { '?', '!', '$', '€', '%' };
char[] letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.Write("Choose your password length: ");
pwlength = Convert.ToInt32(Console.ReadLine());
Console.Write("Include numbers (Y/N): ");
includeNum = Console.ReadLine();
if (includeNum != "Y" && includeNum != "N")
{
Console.WriteLine("Invalid answer - Only answer the letter Y for Yes and N for No! ");
Console.Write("Include numbers (Y/N): ");
includeNum = Console.ReadLine();
}
Console.Write("Include symbols? (Y/N): ");
includeSym = Console.ReadLine();
if (includeSym != "Y" && includeSym != "N")
{
Console.WriteLine("Invalid answer - Only answer the letter Y for Yes and N for No! ");
Console.Write("Include symbols? (Y/N): ");
includeSym = Console.ReadLine();
}
Random rnd = new Random();
for (int z = 1; z <= pwlength; z++)
{
int rndList = rnd.Next(1, 4);
if (rndList == 1)
{
int rndChar = rnd.Next(0, 53);
Console.Write(letters[rndChar]);
}
else if (rndList == 2)
{
int rndNum = rnd.Next(0, 11);
Console.Write(nums[rndNum]);
}
else if (rndList == 3)
{
int rndSym = rnd.Next(0, 6);
Console.Write(symbols[rndSym]);
}
}
Console.ReadKey();
}
}
}