Joshua tang
Joshua tang

Reputation: 1

Creating a random Generator from a text file on c#

I’m pretty new to c# and recently I’m trying out a random generator using fruits from a text file for example Apples Oranges Pears Kiwis

.. and so on. However I wasn’t able to do it as I didn’t have unixengine installed to run the random.next command. Is there another way where I can draw the input from the text file as an array then use a command to randomise the output without duplicating.

Apparently I can’t run my codes about and I’m at a lost at what to do! Sorry again! I just started c# a few weeks ago! Any help to guide me would help a lot!

Upvotes: 0

Views: 1418

Answers (1)

Rolwin Crasta
Rolwin Crasta

Reputation: 4339

First read the text file as string into a string variable Code below (you need to include system.IO)

string fruits = File.ReadAllText(@"c:\fruits.txt", Encoding.UTF8);

Next Split the Text into an array of stings (assuming the fruits are separated by an space character on the text file)

string[] fruitsArray = fruits.Split(' ');

Next generate a random number from 0 to the number of fruits in Fruit Array -1 (Arrays starts with index 0)

Random rnd = new Random();
int fruitNumber = rnd.Next(0, fruitsArray.Length); // return number between 0 and (Length -1)

Now using this random number pick the fruit at the random position from the fruitsarray,

string output = fruitsArray[fruitNumber];

Upvotes: 1

Related Questions