【问题标题】:C# Randomly Choosing Word Not Working [duplicate]C#随机选择单词不起作用[重复]
【发布时间】:2017-09-30 12:53:35
【问题描述】:

我正在开发一个刽子手游戏,每次通过调试我发现尽管guessIndex 生成了一个数字,但它并没有从单词数组中选择一个单词。我已经调试过,我知道 100% 它创建了一个数字,但 currentWord 仍然为空。谁能帮忙解决这个问题?

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 行

【问题讨论】:

  • 您应该不在每次需要新的随机数时创建一个新的随机实例。您应该创建一个 Random 实例并在需要新的随机值时重用它。
  • 第 58 行 ... 特别方便知道,因为我们这里没有行号 ...

标签: c# arrays random


【解决方案1】:

问题出在您的LoadWords 方法中:这一行

words = new string[readText.Length];

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

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

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

【讨论】:

  • 我明白了,所以我创建了一个 null 数组,因为我说的是新字符串?干杯!
  • @LiamVallance 当你创建一个新数组时,它的元素被初始化为数组元素类型的默认值。对于string 和其他引用类型,默认值为null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
相关资源
最近更新 更多