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

本文关键字:添加 单词 cmd 项目 自己的 System 何使用 collections generic 用户 | 更新日期: 2023-09-27 18:30:37

嗨,这次我试图允许用户将自己的单词添加到随机句子生成器中。 目前,它从数组中选择一个随机单词并将其替换为 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);


    }
}
}

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

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)]

还要重新考虑如何使用 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 );