user3644837
user3644837

Reputation: 345

c# loading text from textfile into multiple textBoxes at random

I have a textfile called answers.txt. In this textfile I have stated a few answers like this:

    answer1 | answer2 | answer3 |...

Now to read these answers I made a class called answeres and it contains this code:

     public String getAnswer(int number)
    {
        stream = File.OpenText("answers.txt");
        String[] answers;
        string line = stream.ReadLine();
        vragen = line.Split('|');
        return answers[number];
    }

In my mainForm where I need to get these text's displayed I have 4 Labels. I want these labels to show these answers in random order. I did it like this:

    public form1()
    {
        InitializeComponent();
    }

    private answer answer1 = new answer();
    private int rand = 0;

    private void form1_Load(object sender, EventArgs e)
    {
        label1.Text = answer1.getAnswer(rand); }

Now this isn't random (which I would like) & also this only works for one Label. How can I display the textfile on the multiple labels at random while making sure none of the labels show the same text from the textfile?

Thanks in advance.

Upvotes: 0

Views: 563

Answers (2)

quantdev
quantdev

Reputation: 23813

Read the file once (instead of reading it at each getAnswer() call)

public List<String> ReadAllAnswers()
{
    stream = File.OpenText("answers.txt");
    String[] answers;
    string line = stream.ReadLine();
    return line.Split('|', StringSplitOptions.RemoveEmptyEntries);
}

Put all the answers in a list, an shuffle it with a method like this:

ReadAllAnswers()
Random rnd = new Random();
answers = answers.OrderBy<string, int>((item) => rnd.Next());

Then, assign label0 with answers[0] ... labelN with answers[N]

label1.Text = answers.getAnswer(0);
//...
label4.Text = answers.getAnswer(3);

Upvotes: 1

James Fleming
James Fleming

Reputation: 2589

Well, since it is better to teach a man to fish instead of give him a fish. It seems to that you need to clarify in your head each of the steps. The best way to to this is to write out the pseudo-code for what you are trying to do.

  1. Load answers into memory
  2. convert answers into an array
  3. create a randomizer that returns a list of numbers of a specific length
  4. That list of numbers must only contain numbers less than the length of the array
  5. That list must not contain the same number twice.
  6. Take this new list and iterate over your collection of answers
  7. pull the answers from the array and assign to the labels.

This list could certainly be improved. Break down the tasks into manageable bits of logic via pseudo code Each task becomes a function that is named according to its task.

A great book on programming (not C#) is Code Complete

Happy programming!

Upvotes: 0

Related Questions