如何使用System.collections.generic让用户将自己的单词添加到cmd项目中

时间:2014-11-17 18:32:07

标签: c# generics

嗨,这次我试图让用户将自己的单词添加到随机句子生成器中。此刻它从数组中选取一个随机单词并将其替换为WriteLine语句,现在我想让用户输入单词然后进入下一个生成的句子。我告诉我需要使用System.collections.generic List(t),但我仍然坚持如何这样做。到目前为止,这是我的代码......

using System;

namespace sentenceGenerator
{
class MainClass
{
    public static void Main (string[] args)
    {
        Random random = new Random ();

        Console.WriteLine ("****************************************");
        Console.WriteLine ("Welcome To The Random Sentence Generator");
        Console.WriteLine ("****************************************");
        Console.WriteLine ("Type " + "Exit" + " If You Wish To Exit The Program");
        Console.WriteLine ("*****************************************");
        Console.WriteLine ("Press Enter To Generate Another Random Sentence");
        Console.WriteLine ("***********************************************");

        do {

            string[] Nouns = new string [] // Nouns Array
        { "Dog", "Cat", "Snake", "Rhino", "Rat", "Horse", "Bear", "Lynx", "Octopus", "Skunk",     "Toucan", "Tortoise", "Donkey", "Tiger", "Lion", "Jaguar", "Duck", "Hamster", "Cow", "Sloth",     "Gecko" };
            string[] Verb = new string [] // Verbs Array
        { "licked", "killed", "fought", "ate", "swallowed", "stepped on", "squashed" };
            string[] Adjective = new string [] // Adjectives Array
            { "small", "cute", "big", "fat", "thin", "furry", "huge", "tiny" };
            Console.WriteLine("----------------------");
            Console.WriteLine("A " + Adjective [random.Next (0, Nouns.Length)] + Nouns     [random.Next (0, Nouns.Length)] + " " + Verb [random.Next (0, Verb.Length)] + " a " + Adjective     [random.Next (0, Nouns.Length)] + Nouns [random.Next (1, Nouns.Length)]); 
            Console.WriteLine("----------------------");

            // Exit Code
            string exit = Console.ReadLine();

            if (exit == "exit"){
                break;
            }
            //

        } while (true);




    }
}
}

2 个答案:

答案 0 :(得分:2)

List<T>是一个集合;就像一个数组。列表的优点是它具有可变数量的元素

所以不是数组;声明List<string>

List<string> adjectives = new List<string> // Adjectives List
            { "small", "cute", "big", "fat", "thin", "furry", "huge", "tiny" };

并添加(来自用户输入):

string userInputString = Console.ReadLine();
adjectives.Add(userInputString);

最后,在确定随机最大值时使用Count代替Length

adjectives[random.Next(adjectives.Count)]

答案 1 :(得分:0)

还要重新考虑如何使用Console.WriteLine:

Console.WriteLine("A " + Adjective [random.Next (0, Nouns.Length)] + Nouns     [random.Next (0, Nouns.Length)] + " " + Verb [random.Next (0, Verb.Length)] + " a " + Adjective     [random.Next (0, Nouns.Length)] + Nouns [random.Next (1, Nouns.Length)]); 

更改为:

string adjective = Adjective [random.Next (0, Nouns.Length)];
...
Console.WriteLine( "A {0} {1} a {2}", adjective, verb, noun );