I have a random key generator in C# that's supposed to generate a key in the following format:
consonant + vowel + consonant + vowel + four numerical digits
So for example it would be BABA1234 or ZUZU9876.
Currently, however, the vowels don't show up, though everything else does, so I end up getting output like B_B_1234, for example, where the underscores represent either spaces or unrecognized character boxes.
I've been looking through some examples such as this, this and this, but I still haven't gotten it to work. The C# code is as follows:
public static string shortText()
{
string randomNumber = new Random().Next(1000, 9999).ToString();
char c1 = consonant();
char c2 = vowel();
System.Threading.Thread.Sleep(400);
char c3 = consonant();
char c4 = vowel();
return string.Format("{0}{1}{2}{3}{4}", c1, c2, c3, c4, randomNumber);
}
private static char vowel()
{
int selected = new Random().Next(0, 4);
List<int> list = new List<int> { 65, 69, 73, 79, 85 };
return Strings.Chr(selected);
}
private static char consonant()
{
int selected = new Random().Next(65, 90);
List<int> list = new List<int> { 65, 69, 73, 79, 85 };
if (list.Contains(selected) == false)
{
return Strings.Chr(selected);
}
else {
return Strings.Chr(selected + 1);
}
}
An additional note is that this code was originally written in VB (which is why there is a Strings.Chr in the C# code above, I added a reference to the VB library), where it worked correctly and generated codes according to the format in the beginning. I converted it over to C# and edited it slightly to remove the errors, but it looks like the conversion hasn't been perfect. Here is the VB code:
Public Class Form1
Private Sub btnGenerateKey_Click(sender As Object, e As EventArgs) Handles btnGenerateKey.Click
txtKey.Text = shortText()
End Sub
Private Shared Function shortText() As String
Dim randomNumber As String = New Random().Next(1000, 9999).ToString
Dim c1 As Char = consonant()
Dim c2 As Char = vowel()
System.Threading.Thread.Sleep(400)
Dim c3 As Char = consonant()
Dim c4 As Char = vowel()
Return String.Format("{0}{1}{2}{3}{4}", c1, c2, c3, c4, randomNumber)
End Function
Private Shared Function vowel() As Char
Dim list As List(Of Integer) = New List(Of Integer)({65, 69, 73, 79, 85})
Return Chr(list(New Random().Next(0, 4)))
End Function
Private Shared Function consonant() As Char
Dim selected As Integer = New Random().Next(65, 90)
Dim list As List(Of Integer) = New List(Of Integer)({65, 69, 73, 79, 85})
If list.Contains(selected) = False Then
Return Chr(selected)
Else
Return Chr(selected + 1)
End If
End Function
End Class
Any help is much appreciated.
Aucun commentaire:
Enregistrer un commentaire