-3

I am trying to make a simple program that makes a list of words then it picks a random word and then it prints that word. Everything works but I just can't seem to make the program print the word. This is my code so far.

using System;
using System.Collections.Generic;

namespace Hangman

{
    class Program
    {

    List<String> words = new List<String> { "cat", "police", "conjuring", "sand", "hoppleflink", "defenestrait", "cumberground", "sexy shreck" };

    public string PickRandom()
    {
        var random = new Random();
        var wordCount = words.Count;
        var randomNum = random.Next(wordCount);
        var randomWord = words[randomNum];
        return randomWord;


    }

    static void Main(string[] args)
    {
        Console.WriteLine(); 
    }

}

}

Ipsit Gaur
  • 2,872
  • 1
  • 23
  • 38

1 Answers1

1

To make your code work, you need to print a value rather than nothing, as you currently are.

At the moment, your words field and PickRandom method are instance members, so Main (a static method) cannot use them without an instance of Program. So, first, we'll create an instance of Program:

Program program = new Program();

Then we'll take a random word:

string word = program.PickRandom();

And finally we'll write it:

Console.WriteLine(word);

Putting it all together:

static void Main(string[] args)
{
    Program program = new Program();
    string word = program.PickRandom();
    Console.WriteLine(word); 
    // keep the console open after the code has executed by waiting for a keypress
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(); 
}

You can read about static vs instance members here.

You'll probably run up against an issue with Random soon - if you call your PickRandom method too frequently, you'll find that you get the same value repeated. The reason why is explained in this post. TL;DR: The seed value is based on time, so if you create two instances of Randomat the exact same time, you'll get the same seed value.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86