C#随机选择Word不工作

时间:2017-09-30 12:53:35

标签: c# arrays random

我正在制作一个刽子手游戏,每次通过调试我发现尽管guessIndex生成一个数字但它没有从单词数组中选择一个单词。我调试了,我知道100%它创建了一个数字,但currentWord仍然是null。任何人都可以帮忙解决这个问题吗?

namespace Guess_The_Word
{

    public partial class Form1 : Form
    {
        private int wrongGuesses = 0;
        private int userGuesses;
        private string secretWord = String.Empty;
        private string[] words;
        private string currentWord = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadWords();
            setUpWords();

        }

        private void guessBtn_Click(object sender, EventArgs e)
        {

            wrongGuesses++;
            if (wrongGuesses <= 0)
            {
                MessageBox.Show("You have lost! The currect word was {0}", currentWord);
            }
        }

        private void LoadWords()
        {

            string path = (@"C:\commonwords.txt"); // Save the variable path with the path to the txt file
            string[] readText = File.ReadAllLines(path);
            words = new string[readText.Length];
        }

        private void setUpWords()
        {
            wrongGuesses = 0;
            int guessIndex = (new Random()).Next(words.Length);
            currentWord = words[guessIndex];
            userGuesses = currentWord.Length;

        }
        private void ResetGame()
        {

            //.Show("You have {0} guesses for this word, guess three in a row to win!");
        }

        private void resetGamebtn_Click(object sender, EventArgs e)
        {
            LoadWords();

        }
    }
}

我明白了 System.NullReferenceException:'对象引用未设置为对象的实例。'

第58行

1 个答案:

答案 0 :(得分:2)

问题在于您的LoadWords方法:此行

words = new string[readText.Length];

创建一个null长度为readText.Length的字符串数组。您需要按如下方式重写该方法:

private void LoadWords() {
    string path = @"C:\commonwords.txt";
    words = File.ReadAllLines(path);
}

现在words将包含来自string文件的非空C:\commonwords.txt对象数组。