Reputation: 345
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
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
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.
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