Visual C# Random Number File Writer - c#

private void btn_Save_Click(object sender, EventArgs e)
{
// Declare int variable.
int randomNumber = 0;
// Declare a StreamWriter variable.
StreamWriter outputFile;
// Get the number of random integers to hold in file.
int number = int.Parse(txt_Number.Text);
if (saveFile.ShowDialog() == DialogResult.OK)
{
// Create the selected file.
outputFile = File.CreateText(saveFile.FileName);
// Create a Random Object.
Random Rand = new Random();
for (int count = 0; count < number; count++)
{
// Get random integers and assign them to randomNumber.
randomNumber = Rand.Next(1, 101);
// Write data to the file.
outputFile.WriteLine(randomNumber);
// Close the file.
outputFile.Close();
MessageBox.Show("File saved in path:" + saveFile.FileName);
}
}
else
{
// Display an error message.
MessageBox.Show("Operation Cancelled");
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
// Clear the TextBox.
txt_Number.Text = "";
}
private void btn_Exit_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
The question is: Create a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user specify how many random numbers the file will hold.
The code is working but i' having problems with the output writeline.
Each time i'm running the program, it says exception unhandled and cannot write to a Closed TextWriter.
Also instead of saving multiple random numbers, it is saving only one.
Any help concerning these 2 problems would be great.

Your error is in the for loop here:
for (int count = 0; count < number; count++)
{
// Get random integers and assign them to randomNumber.
randomNumber = Rand.Next(1, 101);
// Write data to the file.
outputFile.WriteLine(randomNumber);
// Close the file.
outputFile.Close();
MessageBox.Show("File saved in path:" + saveFile.FileName);
}
You close the file before iterating through all the numbers. Thus, you cannot write past the first number. The close function should be outside the for loop like so:
for (int count = 0; count < number; count++)
{
// Get random integers and assign them to randomNumber.
randomNumber = Rand.Next(1, 101);
// Write data to the file.
outputFile.WriteLine(randomNumber);
MessageBox.Show("File saved in path:" + saveFile.FileName);
}
// Close the file outside for loop
outputFile.Close();

Related

Random Number Generator using C#

I'm needing to create random numbers based on the number of random numbers needed by a user.
The user can then save those random numbers to a file when the save to file button is clicked.
After that, the program allows the user to open the same file, but this time, the file opened needs to display how many random numbers within a specific range were created.
The ranges are: (0-19, 20-39, 40-59, 60-79, and 80-99).
So far I'm able to create one random number and list the same number over the number of times entered by the user, but unfortunately:
The random numbers created need to all be random through the number of iterations created by the user.
I don't know how to display the numbers within their respective range.
I can't display the numbers properly.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void RandNumbtextBox_TextChanged(object sender, EventArgs e)
{
}
private void saveFileButton_Click(object sender, EventArgs e)
{
double randomNumber = double.Parse(RandNumbtextBox.Text);
Random r = new Random();//random number object
int random = r.Next(1, 10);// random number 1
if (saveFileDialog.ShowDialog()== DialogResult.OK)
{
StreamWriter outputFile;
outputFile = File.CreateText(saveFileDialog.FileName + ".txt");
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(random.ToString());
}
outputFile.Close();
}
else
{
MessageBox.Show("op cancelled");
}
}
private void openFileButton_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
StreamReader inputFile;
inputFile = File.OpenText(openFileDialog.FileName);
int sum = 0;
while (!inputFile.EndOfStream)
{
sum += int.Parse(inputFile.ReadLine());
}
inputFile.Close();
MessageBox.Show(sum.ToString());
}
else
{
MessageBox.Show("op cancelled");
}
}
}
Thanks to John I was able to figure out the first issue of the question. Generating the random number issue and write them to file.
I'm still unable to:
*Display the numbers within their respective range.
I can't display the numbers properly.
OP, you are assigning the random number once:
int random = r.Next(1, 10);// random number 1
And then writing it out randomNumber times:
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(random.ToString());
}
I think your code needs to read:
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(r.Next(1, 10).ToString());
}
As for counting numbers in ranges: A simple approach might be to create "count" variables for each range, and implement branching logic to increment the correct one depending on the number you're looking at. A more dynamic approach may involve a dictionary, or an array of classes which contain the range and a count value.

cycle never reaching final value

This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.
Without the if statement it works, but it won't fill the range needed.
fixed the code, now works OK, the initial value in array was the problem. now I ged needed 0-29 values
public partial class Form1 : Form
{
int[] rndCards = new int[30];
public Form1()
{
InitializeComponent();
richTextBox1.Text = #"random numbers";
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
rndCards = new int[30];
richTextBox1.Clear();
Random rnd = new Random();
while (i < 30)
{
int cardTest = rnd.Next(0, 30);
while (rndCards.Contains(cardTest))
{
cardTest++;
if (cardTest == 31)
{
cardTest = 1;
}
}
rndCards[i] = cardTest;
i++;
}
i = 0;
while (i < 30)
{
rndCards[i] = rndCards[i] -1;
richTextBox1.Text += rndCards[i] + ", ";
i++;
}
}
}
You problem lies in the simple fact that the array already contains the number 0 when you create it (because each item of an array is initialized to the default value for its member's type) That's why you should start your i from 1 and not zero.
int i = 1;
Alternative Simpler Approach:
You can do this as a simple random number generation:
Random rnd = new Random();
rndCards = Enumerable.Range(0, 30).OrderBy(x => rnd.Next()).ToArray();
foreach(var card in rndCards)
{
// do something
}
rnd.Next(0,30) would return a random number from 0-29.
From the documentation for Random.Next(Int32, Int32):
The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.
Use int cardText = rnd.Next(0, 31);, and this should solve your issue.
The upper bound is exclusive (C# Random.Next - never returns the upper bound?).
int cardTest = rnd.Next(0, 31);

Generate Random number in C# [duplicate]

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 6 years ago.
I am wanting to generate a random number between 1 and 10. Yet I am getting a couple of errors.
public Form1()
{
InitializeComponent();
}
int randomNumber = (0, 11);
int attempts = 0;
public int RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
}
}
it is all on the 0, 11 under the comma is says --> struct System.Int32 represents a 32-bit signed integer <--. Under the 11 it says --> Identifier expected Syntax error, ',' expected <--. Now if I just have like int randomNumber = 0; then it will work fine, still have multiple guesses and the guess count adds up like it should, and have the too high too low labels. just the number will always be 0.
Also how can I make it to where I don't have to click the guess button, I can just hit enter on the keyboard?
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";
else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
else
{
label1.Text = "You won.";
textBox1.Enabled = false;
label2.Text = "Attempts: 0";
textBox1.Text = String.Empty;
MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
attempts = 0;
label2.Text = "Attempts: " + attempts.ToString();
return;
}
attempts++;
label2.Text = "Attempts: " + attempts.ToString();
}
catch { MessageBox.Show("Please enter a number."); }
}
To generate a Random number you have to usw the System.Random class. Your syntax can look something like this :
System.Random rng = new System.Random(<insert seed if you want>);
int randomNumber = rng.Next(1,11);
You have to do rng.Next(1,11) since the lower bound is include (1 is a possible result) and the upper bound is exclude (11 isnt getting added into the pool oft possible results).
To do implement your Enter shortcut you have to add a method to your Forms KeyPress event in which you call the button1_clicked method.
button1_Clicked_1(this, System.EventArgs.Empty);
At last you have to set your forms "KeyPreview" property to true.
You can use something like the below code to generate random number between 1 to 10
Random randomNumberGenrator = new Random();
int num = randomNumberGenrator.Next(10) + 1;
Take a look at this.
Use the Random class in order to generate a random number.
private Random _rnd = new Random();
private int RandomNumber
{
get
{
return _rnd.Next(0,11);
}
set
{
this = value;
}
}

Application only works correctly if I have messagebox in the code

I have a button event in which generates some random numbers based upon the number typed into a textbox (for example, if I type 5, it should generate 5 different random numbers). When I type in a number into the textbox, and click the btnGenerateScores button, it generates a single number and puts that number in the listbox 5 times (or however many times based upon the number in the textbox). This behavior is not correct, it should generate 5 different numbers and list each in the listbox. If I put a MessageBox.Show (I was using it for debugging) command anywhere in the code block, it works correctly. Commenting out the MessageBox.show breaks the code. Does anyone see any reason why it would not work correctly when I don't show the message box? The code is below:
private void btnGenerateScores_Click(object sender, EventArgs e)
{
strInput = txtInputNumber.Text;
intRandCount = Convert.ToInt16(strInput);
scoresArray = new int[intRandCount];
intArrayCount = scoresArray.Length;
btnGenerateScores.Enabled = false;
// Loop to generate random number
for (intRndCount = 0; intRndCount < intRandCount; intRndCount++)
{
GetRand(intRandCount);
scoresArray[intCount] = intRandomNum;
intGenRandom = intRandomNum;
intArrScores = scoresArray[intCount];
lstRdmScores.Items.Add(Convert.ToString(intArrScores));
insertionSortArray = new int[intArrayCount];
Array.Copy(scoresArray, insertionSortArray, intArrayCount);
// Instantiate an instance of the class
arraySort mySort = new arraySort();
// Get the number of elements to store in the array
string s = Convert.ToString(intCount);
mySort.x = Int16.Parse(s);
// Get array elements
for (int i = 0; i < mySort.x; i++)
{
intInsertionSort = insertionSortArray[intCount];
string s1 = Convert.ToString(intInsertionSort);
mySort.a[i] = Int16.Parse(s1);
}
// Sort the array and display in the second list box
mySort.sortArray();
intSortScores = insertionSortArray[intCount];
lstSortScores.Items.Add(Convert.ToString(intSortScores));
// This is the the MessageBox.Show command in question:
MessageBox.Show("The random number generated is: "); //+ Convert.ToString(intGenRandom));
}
}
ignore the fact that the array does not sort correctly, I will get to that later. I want to work on one thing at a time.
I am using VS 2013 and the code was originally created in VS 2005.
As your requirement, and view the source, I rewrite the app for short:
private void btnGenerateScores_Click_1(object sender, EventArgs e)
{
int genTimes;
if (Int32.TryParse(txtInputNumber.Text, out genTimes))
{
var ints = new List<int>();
for (var i = 0; i < genTimes; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
var rInt = r.Next(0, int.MaxValue); //for ints
ints.Add(rInt);
}
var copyInts = ints.ToList();
copyInts.AddRange(this.listBox1.Items.Cast<int>());
copyInts = copyInts.Distinct().OrderBy(x => x).ToList();
this.listBox1.Items.Clear();
this.listBox1.Items.AddRange(copyInts.Cast<object>().ToArray());
MessageBox.Show("The random number generated is: " + String.Join(",", ints));
}
}
}
Hope this help.

Flip a coin problem

I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}

Categories

Resources