因此,我在c#中做了一個非常簡單的字生成器程序,該程序運行得相當好。它根據用戶定義的長度生成一個單詞。隨機字生成器#2
該算法爲序列中的每個連續字母添加一個輔音,然後是一個元音,這並不理想,但對於基本單詞的效果不錯。
我唯一的問題是,我告訴它之前,它的權利添加一個「U」的字母序列,如果「Q」表示,但無論我做什麼它使這個詞至少1個字母太長。
我在上面的註釋中用星號標記了我的問題區域。下面是代碼:
public void WordFinder()
{
string word = null;
int cons;
int vow;
//counter
int i = 0;
bool isword = false;
Random rnd = new Random();
//set a new string array of consonants
string[] consonant = new string[]{"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"};
//set a new string array of vowels
string[] vowel = new string[]{"a","e","i","o","u"};
while (isword == false)
{
word = null;
Console.WriteLine("Pick the length of a word");
int num = Convert.ToInt32(Console.ReadLine());
//set the counter "i" to 1
i = 1;
if (num%2 == 0)
{
while (i <= num)
{
if (num != 1)
{
// current consonant = random consonant
cons = rnd.Next(0, 20);
// get the consonant from the string array "consonant" and add it to word
word = word + consonant[cons];
// add 1 to counter
i ++;
//* if the consonant is "q"
if (cons == 12)
{
// add "u" right after it
word = word + vowel[4];
// add 1 to counter
i++;
}
}
vow = rnd.Next(0, 4);
word = word + vowel[vow];
i ++;
}
}
if (num % 2 != 0)
{
while (i <= num - 1)
{
//repeat same code as done to even length
if (num != 1)
{
cons = rnd.Next(0, 20);
word = word + consonant[cons];
i ++;
if (cons == 12)
{
word = word + vowel[4];
i ++;
}
}
vow = rnd.Next(0, 4);
word = word + vowel[vow];
i ++;
}
// if the length is not equal to 1
if (num != 1)
{
// add a consonant to the end of the word
cons = rnd.Next(0, 20);
word = word + consonant[cons];
}
//if the length is 1
else if (num == 1)
{
// pick a vowel
vow = rnd.Next(0, 4);
word = word + vowel[vow];
}
}
i = 1;
Console.WriteLine(word);
Console.WriteLine("Is this a word? (y/n)");
string q = Console.ReadLine();
q = q.ToLower();
//if the answer is yes, then it is a word and end the loop
if (q == "y" || q == "yes")
{
isword = true;
}
//if the answer is no try the loop again
else if (q == "n" || q == "no")
{
isword = false;
}
}
}
// main method
static void Main(string[] args)
{
Program prog = new Program();
prog.WordFinder();
//wait for user input
Console.ReadLine();
}
}
該代碼中的幾乎所有註釋都沒有幫助。評論應該在那裏告訴你,代碼*不會告訴你(或者代碼中不明顯)的信息。只是說明代碼的作用並不能幫助任何人,但這隻會浪費人們的時間。 – Servy
我不明白*它是什麼使它成爲一個字母(或者在「u」長*之後添加了「q」的次數)意味着你可以嘗試使用'consonant [cons] =='q' '作爲你的'if'條件,而不是你在那裏的神奇數字12 –
我讀這個的方式是,每循環一次,你要加2個字母,一個輔音和一個元音。一個'Q'你總共添加了3個字母:'QU'加上一個隨機的其他元音,這裏的邏輯看起來有點不對頭 – NotMe