从列表中选择随机单词?

我在从另一个文件的列表中选择一个随机单词时遇到问题。 实际上我甚至不能选择任何单词。 我不知道如何连接2个文件这么说。 希望有人可以提供帮助,我是初学者所以请尽可能简单地解释:)

我有2个文件,一个叫做program.cs,另一个叫做WordList.cs我会粘贴我的所有代码,但首先是我有问题的小剪辑。 我只是不知道如何编写正确的代码。

这是一个叫做Pick word的小部分:

//PICK WORD static string pickWord() { string returnword = ""; TextReader file = new StreamReader(words); string fileLine = file.ReadLine(); Random randomGen = new Random(); returnword = words[randomGen.Next(0, words.Count - 1)]; return returnword; } 

这是Program.cs中的所有代码

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; class Hangman { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.Title = "C# Hangman"; Console.WriteLine("Welcome To C# Hangman!"); //MENU int MenuChoice = 0; while (MenuChoice != 4) { Console.Write("\n\t1) Add words"); Console.Write("\n\t2) Show list of words"); Console.Write("\n\t3) Play"); Console.Write("\n\t4) Quit\n\n"); Console.Write("\n\tChoose 1-4: "); //Choose meny item MenuChoice = Convert.ToInt32(Console.ReadLine()); WordList showing = new WordList(); switch (MenuChoice) { case 1: Console.Write("\n\tAdd a word\n\n"); var insert = Console.ReadLine(); showing.AddWord(insert); Console.Write("\n\tList of words\n\n"); showing.ListOfWords(); break; case 2: Console.Write("\n\tList of words\n\n"); showing.ListOfWords(); break; case 3: //Running game int numGuessesInt = -1; while (numGuessesInt == -1) { /* Sets the number of guesses the user has to guess the word*/ pickNumGuesses(ref numGuessesInt); } /* Randomly picks a word*/ string word = pickWord(); /* Creates a list of characters that will show */ List guessedLetters = new List(); bool solved = false; while (solved == false) { /* Displaying a string to the user based on the user's correct guesses. * If nothing is correct string will return "_ _ _ " */ string wordToDisplay = displayWord(guessedLetters, word); /* If the string returned contains the "_" character, all the * correct letters have not been guessed, so checking if user * has lost, by checking if numGuessesLeft is less than 1.*/ if (!wordToDisplay.Contains("_")) { solved = true; Console.WriteLine("You Win! The word was " + word); /* Check if the user wants to play again. If they do, * then solved is set to true, will end the loop, * otherwise, checkIfPlayAgain will close the program.*/ checkIfPlayAgain(); } else if (numGuessesInt <= 0) { solved = true; Console.WriteLine("You Lose! The word was " + word); checkIfPlayAgain(); } else { /* If the user has not won or lost, call guessLetter, * display the word, minus guesses by 1*/ guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt); } } break; case 4: Console.WriteLine("\n\tEnd game?\n\n"); break; default: Console.WriteLine("Sorry, invalid selection"); break; } } } // ****** PICK NUMBER OF GUESSES ****** static void pickNumGuesses(ref int numGuessesInt) { string numGuessesString = ""; Console.WriteLine("Pick a number of guesses"); numGuessesString = Console.ReadLine(); try { numGuessesInt = Convert.ToInt32(numGuessesString); if (!(numGuessesInt = 1)) { throw new Exception(); } } catch (Exception) { numGuessesInt = -1; Console.WriteLine("Error: Invalid Number of Guesses"); } } //PICK WORD static string pickWord() { string returnword = ""; TextReader file = new StreamReader(words); string fileLine = file.ReadLine(); Random randomGen = new Random(); returnword = words[randomGen.Next(0, words.Count - 1)]; return returnword; } // ****** Display word ****** static string displayWord(List guessedCharacters, string word) { string returnedWord = ""; if (guessedCharacters.Count == 0) { foreach (char letter in word) { returnedWord += "_ "; } return returnedWord; } foreach (char letter in word) { bool letterMatch = false; foreach (char character in guessedCharacters) { if (character == letter) { returnedWord += character + " "; letterMatch = true; break; } else { letterMatch = false; } } if (letterMatch == false) { returnedWord += "_ "; } } return returnedWord; } // ****** Guess letter ****** static void guessLetter(List guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft) { string letters = ""; foreach (char letter in guessedCharacters) { letters += " " + letter; } Console.WriteLine("Guess a letter"); Console.WriteLine("Guessed Letters: " + letters); Console.WriteLine("Guesses Left: " + numGuessesLeft); Console.WriteLine(wordToDisplay); string guess = Console.ReadLine(); char guessedLetter = 'a'; try { guessedLetter = Convert.ToChar(guess); if (!Char.IsLetter(guessedLetter)) { throw new Exception(); } } catch (Exception) { Console.WriteLine("Error: Invalid Letter Choice"); //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft); } bool repeat = false; for (int i = 0; i < guessedCharacters.Count; i++) { if (guessedCharacters[i] == guessedLetter) { Console.WriteLine("Error: Invalid Letter Choice"); repeat = true; //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft); } } if (repeat == false) { guessedCharacters.Add(guessedLetter); numGuessesLeft -= 1; } } // ****** Check to see if player wants to play again. ****** static void checkIfPlayAgain() { Console.WriteLine("Would you like to play again? (y/n)"); string playAgain = Console.ReadLine(); if (playAgain == "n") { Environment.Exit(1); } } } 

这是WordList.cs的代码

 using System; using System.Collections.Generic; class WordList { List  words = new List(); public void ListOfWords() { words.Add("test"); // Contains: test words.Add("dog"); // Contains: test, dog words.Insert(1, "shit"); // Contains: test, shit, dog words.Sort(); foreach (string word in words) // Display for verification { Console.WriteLine(word); } } public void AddWord(string value){ words.Add(value); } } 

我对您的代码进行了一些更改。 代码现在可以使用,但远非完美。 您的解决方案有两个文件Program.csWordlist.cs ,看起来像这样

Program.cs中

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; public class Hangman { /* * Some notes on your code: * use naming convention for methods and fields, ie methods names start with a capital letter * use modifiers for methods, ie private, public, protected in your method declarations * make variables private if you use them on several methods * and finally: read a book on c# * */ private static WordList words; private static Random randomGen = new Random(); public static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Red; Console.Title = "C# Hangman"; Console.WriteLine("Welcome To C# Hangman!"); initializeWordList(); //MENU int MenuChoice = 0; while (MenuChoice != 4) { Console.Write("\n\t1) Add words"); Console.Write("\n\t2) Show list of words"); Console.Write("\n\t3) Play"); Console.Write("\n\t4) Quit\n\n"); Console.Write("\n\tChoose 1-4: "); //Choose meny item MenuChoice = Convert.ToInt32(Console.ReadLine()); switch (MenuChoice) { case 1: Console.Write("\n\tAdd a word\n\n"); var insert = Console.ReadLine(); words.Add(insert); Console.Write("\n\tList of words\n\n"); foreach (string w in words) // Display for verification Console.WriteLine(w); break; case 2: Console.Write("\n\tList of words\n\n"); foreach (string w in words) // Display for verification Console.WriteLine(w); break; case 3: //Running game int numGuessesInt = -1; while (numGuessesInt == -1) { /* Sets the number of guesses the user has to guess the word*/ pickNumGuesses(ref numGuessesInt); } /* Randomly picks a word*/ string word = PickWord(); /* Creates a list of characters that will show */ List guessedLetters = new List(); bool solved = false; while (solved == false) { /* Displaying a string to the user based on the user's correct guesses. * If nothing is correct string will return "_ _ _ " */ string wordToDisplay = displayWord(guessedLetters, word); /* If the string returned contains the "_" character, all the * correct letters have not been guessed, so checking if user * has lost, by checking if numGuessesLeft is less than 1.*/ if (!wordToDisplay.Contains("_")) { solved = true; Console.WriteLine("You Win! The word was " + word); /* Check if the user wants to play again. If they do, * then solved is set to true, will end the loop, * otherwise, checkIfPlayAgain will close the program.*/ checkIfPlayAgain(); } else if (numGuessesInt <= 0) { solved = true; Console.WriteLine("You Lose! The word was " + word); checkIfPlayAgain(); } else { /* If the user has not won or lost, call guessLetter, * display the word, minus guesses by 1*/ guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt); } } break; case 4: Console.WriteLine("\n\tEnd game?\n\n"); break; default: Console.WriteLine("Sorry, invalid selection"); break; } } } private static void initializeWordList() { words = new WordList(); words.Add("test"); // Contains: test words.Add("dog"); // Contains: test, dog words.Insert(1, "shit"); // Contains: test, shit, dog words.Sort(); } // ****** PICK NUMBER OF GUESSES ****** private static void pickNumGuesses(ref int numGuessesInt) { string numGuessesString = ""; Console.WriteLine("Pick a number of guesses"); numGuessesString = Console.ReadLine(); try { numGuessesInt = Convert.ToInt32(numGuessesString); if (!(numGuessesInt <= 20 & numGuessesInt >= 1)) { throw new Exception(); } } catch (Exception) { numGuessesInt = -1; Console.WriteLine("Error: Invalid Number of Guesses"); } } //PICK WORD private static string PickWord() { return words[randomGen.Next(0, words.Count() - 1)]; } // ****** Display word ****** private static string displayWord(List guessedCharacters, string word) { string returnedWord = ""; if (guessedCharacters.Count == 0) { foreach (char letter in word) { returnedWord += "_ "; } return returnedWord; } foreach (char letter in word) { bool letterMatch = false; foreach (char character in guessedCharacters) { if (character == letter) { returnedWord += character + " "; letterMatch = true; break; } else { letterMatch = false; } } if (letterMatch == false) { returnedWord += "_ "; } } return returnedWord; } // ****** Guess letter ****** static void guessLetter(List guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft) { string letters = ""; foreach (char letter in guessedCharacters) { letters += " " + letter; } Console.WriteLine("Guess a letter"); Console.WriteLine("Guessed Letters: " + letters); Console.WriteLine("Guesses Left: " + numGuessesLeft); Console.WriteLine(wordToDisplay); string guess = Console.ReadLine(); char guessedLetter = 'a'; try { guessedLetter = Convert.ToChar(guess); if (!Char.IsLetter(guessedLetter)) { throw new Exception(); } } catch (Exception) { Console.WriteLine("Error: Invalid Letter Choice"); //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft); } bool repeat = false; for (int i = 0; i < guessedCharacters.Count; i++) { if (guessedCharacters[i] == guessedLetter) { Console.WriteLine("Error: Invalid Letter Choice"); repeat = true; //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft); } } if (repeat == false) { guessedCharacters.Add(guessedLetter); numGuessesLeft -= 1; } } // ****** Check to see if player wants to play again. ****** static void checkIfPlayAgain() { Console.WriteLine("Would you like to play again? (y/n)"); string playAgain = Console.ReadLine(); if (playAgain == "n") { Environment.Exit(1); } } } 

Wordlist.cs

 using System; using System.Collections.Generic; public class WordList : List { } 

这是一个非常简单的解决方案:

只填充一次列表,或者在添加任何单词时,请调用此方法。 码:

 private void PopulateTheWordList() { Console.Write("\n\tAdd a word\n\n"); WordList.Add(Console.ReadLine()); } 

现在只需调用此方法来获取随机单词:

 private string PickWord() { Random ran = new Random(); return WordList[ran.Next(0, WordList.Count)]; } 

如果您需要在另一个类中创建words List ,请使用关键字static

 static List WordList = new List(); 

现在你可以通过编写类名来调用它,比如YourClassName.WordList

尝试创建一个静态类并添加一个返回List的方法,然后您就可以访问您的wordlist了。

例:

 static class WordList { static List words = new List(); public static void ListOfWords() { words.Add("test"); // Contains: test words.Add("dog"); // Contains: test, dog words.Insert(1, "shit"); // Contains: test, shit, dog words.Sort(); foreach (string word in words) // Display for verification { Console.WriteLine(word); } } public static List GetWords() { return words; } public static void AddWord(string value) { words.Add(value); } } 

然后,您可以将switch语句更改为如下所示。

 switch (MenuChoice) { case 1: Console.Write("\n\tAdd a word\n\n"); var insert = Console.ReadLine(); WordList.AddWord(insert); Console.Write("\n\tList of words\n\n"); WordList.ListOfWords(); break; case 2: Console.Write("\n\tList of words\n\n"); WordList.ListOfWords(); break; .... 

你的pickWord方法看起来像这样:

 static string pickWord() { string returnword = ""; Random randomGen = new Random(); returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)]; return returnword; } 

我修改了你的Wordlist类,以便它可以使用一个文件来维护你的程序使用之间的单词,只是因为你被问到这个问题。

 static class WordList { static string filePath = @"C:\temp\Word.txt"; static List words = new List(); private static void CheckFile() { //Makes sure our base words are saved to the file if (!File.Exists(@"C:\temp\Word.txt")) { using (TextWriter writer = new StreamWriter(filePath)) { writer.WriteLine("test"); writer.WriteLine("dog"); writer.WriteLine("shit"); } } } public static void ListOfWords() { CheckFile(); words.Clear(); using (TextReader file = new StreamReader(filePath)) { char[] delineators = new char[] { '\r', '\n' }; string[] tempWords = file.ReadToEnd().Split(delineators, StringSplitOptions.RemoveEmptyEntries); foreach (string line in tempWords) { words.Add(line); } } foreach (string word in words) // Display for verification { Console.WriteLine(word); } } public static List GetWords() { return words; } public static void AddWord(string value) { CheckFile(); using (TextWriter writer = new StreamWriter(filePath,true )) { writer.WriteLine(value); } } }