Random number generator Issue - c#

First off I want to say that I am still a beginner with C#, so when explaining information to me, please do not use complex jargon that I will not understand.
Second, I have done most of the work and I am not asking for others to finish my work, I am just asking for help because I do not understand what is wrong/why it is not working.
Third, my program is incomplete, and I cannot finish it unless my random generator is working.
So with that being said, the issue that I am having is when I try to run the program, the system underlines the word "random" in the beginning of my code and says
"A field initializer cannot reference the non-static field, method, or
property".
Why is it doing this? If I put the two line of code inside "Public Guess()" part then the compiler runs fine, it just then says my "if" statement wont work because the container "random" doesn't exist. I'm not sure of what else I could do and I would really, really, appreciate some help.
My code is as follows:
public partial class Guess : Form
{
/*This is a "Guess the number" program. Then this program is run,
* I want to create two containers for the "TryParse" portion of this program
and then I want a number to be randomly generated for the user to guess, then
I want one last container to count how many guess it took the user.*/
string number;
int guess;
Random random;
int randomnumber;
int counter;
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
random = new Random();
randomnumber = random.Next(0, 101);
}
private void btnClose_Click(object sender, EventArgs e)
{
//This closes the program//
Close();
}
private void btnexe1_Click(object sender, EventArgs e)
{
/*This is where I will be doing most of my variable checking. First,
I want to check if the user left the textbox empty, if it is then
display a message box saying to enter a number.*/
if (string.IsNullOrEmpty(tbnumber.Text))
{
MessageBox.Show("Please enter a number from 0-100.");
}
else
{/*If it is not empty, then I want the system to determine if the variable
that has been entered can be converted to a int.*/
number = Convert.ToString(tbnumber.Text);
if (Int32.TryParse(number, out guess))
{
/*If the value can be converted, then i want the system to see if
it is lower, higher, or equal to the random value. Then I want the fist button hidden,
and the second one shown. Then I want to record how many times the user guessed.*/
if (guess < randomnumber)
{
btnexe1.Hide();
btnexe2.Show();
this.BackColor = System.Drawing.Color.LightSeaGreen;
lbloutput.Text = "Too Low";
counter=counter + 1;
}
else if (guess > randomnumber)
{
btnexe1.Hide();
btnexe2.Show();
this.BackColor = System.Drawing.Color.SlateBlue;
lbloutput.Text = "Too High";
counter = counter + 1;
}
else
{
lbloutput.Text = "Good Guess";
counter = counter + 1;
}
}
else
{
/*If the value cannot be converted to a int, then display a message box saying so.*/
MessageBox.Show("This is not a number. Please enter a number between 0-100.");
}
}
}
private void btnexe2_Click(object sender, EventArgs e)
{/*I want to check if the user left the textbox empty, if it is then
display a message box saying to enter a number.*/
if (string.IsNullOrEmpty(tbnumber.Text))
{
MessageBox.Show("Please enter a number from 0-100.");
}
else
{/*If it is not empty, then I want the system to determine if the variable
that has been entered can be converted to a int.*/
number = Convert.ToString(tbnumber.Text);
if (Int32.TryParse(number, out guess))
{
/*If the value can be converted, then I want the system to see if
it is lower, higher, or equal to the random value. Then I want to record how
many times the user guessed.*/
if (guess < randomnumber)
{
lbloutput.Text = "Too Low";
this.BackColor = System.Drawing.Color.LightSeaGreen;
counter = counter + 1;
}
else if (guess > randomnumber)
{
lbloutput.Text = "Too High";
this.BackColor = System.Drawing.Color.SlateBlue;
counter = counter + 1;
}
else
{
lbloutput.Text = "Good Guess";
counter = counter + 1;
lblcounter.Text = "You guessed " + counter + " times.";
}
}
else
{
/*If the value cannot be converted to a int, then display a message box saying so.*/
MessageBox.Show("This is not a number. Please enter a number between 0-100");
}
}
}
}

Change your code like this. You are trying to call method Next in the class which is not allowed and when you move complete code inside constructor then your variables scope exist only inside that constructor so variable accessed in another method will not work. So solution is to define variable at class level but initialize it in constructor
Random random;
int randomnumber;
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
random = new Random();
randomnumber = random.Next(0, 101);
}

You should initialize variables inside a method (initialization means adding a value to a variable - using "new" keyword);
Try something like this:
class Guess {
Random random;
int randomNumber;
public Guess() {
random = new Random();
randomnumber = random.Next(0, 101);
//Rest of the code
}
}

I think this answer can help you. You can not use an instance variable to initialize another instance variable because the order you write them is not per definition the order the compiler creates them.
A field initializer cannot reference the nonstatic field, method, or property

try changing this
Random random = new Random();
int randomnumber = random.Next(0, 101);
public Guess()
{
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
}
to this
private Random _Random;
private int _RandomNumbrer;
public Guess()
{
_Random = new Random();
_RandomNumbrer = random.Next(0, 101);
/*Once the program is initalized, I want the 2nd button hidden until the first one
is clicked with a value in the textbox*/
InitializeComponent();
btnexe2.Hide();
}
youre nearly there with what youre trying to do

Related

List resetting when adding new items (Edited title to reflect actual issue)

Original Title: Get-Set to add Object w/multiple properties into a list C#
Edit: I had originally thought the issue was in setting up properties for the list objects, when it was an issue with regards to where I had initialized the list in my main code class.
Original Post:
New to coding, taking a C# course. We're working on encapsulation and get:set/properties.
The assignment says that we have to build a class that creates a die with an input number of sides, and "roll" the die for a random number. Easy!
In a second class, we have to build a function to add or remove any number of dice to the pool, and then roll them all for a result.
I'm assuming they want the dice pool to be a list that is private.
My logic going in was to create the single OneDie class, and then using a xDy notation in the main program prompt to add x number of die with y sides to the list. (ie: add 2d6)
I've built an AddDie function that should do that, but when I check my list count after it's done, the count is 0. The private list (_dicePool) seems to be re-setting to zero every time I try to add a new object to the list. I suspect I'm not building my property DicePool's get/set functionality correctly, but I'm not sure how to call my 2-parameter AddDice function from inside the DicePool{set}, or even if that's the approach I should take.
Assuming the list should be private, am I missing something to permanently add new objects to the list?
Edit to add: OR, would it be better to create a ManyDice object? But how do I build this.Sides and this.Roll from the OneDie object?
Here's my code that's applicable to adding objects (dice) to the list (dicepool).
class ManyDice
{
private List<OneDie> _dicePool = new List<OneDie>();
//What I think I might have to do:
public List<OneDie> DicePool
{
get
{
return this._dicePool;
}
set
{
//???????????? how do I call AddDice, when I need 2 parameters for it?
}
}
public void AddDie(int number, int sides)
{
for (int i = 0; i < number; i++)
{
this.dicePool.Add(new OneDie(sides));
}
}
}
class OneDie
{
private int _sides, _rolledValue;
public int Sides
{
get
{
return this._sides;
}
set
{
this._sides = value;
}
}
public int RollValue
{
get
{
return this._rolledValue;
}
set
{
this._rolledValue = value;
RollIt(value);
}
}
public OneDie()
{
}
public OneDie(int sides)
{
this.Sides = sides;
this.RollValue = sides;
}
private int RollIt (int sides)
{
Random random = new Random((int)DateTime.Now.Ticks);
return random.Next(1, (sides + 1));
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Let's roll some dice!");
Console.WriteLine("Please enter the number of dice you want to roll in the following format:");
Console.WriteLine("xdy, where \"x\" is the number of dice you want and \"y\" is how many sides they have.");
Console.WriteLine("Example: 2d6 is 2 6-sided dice. Perfect for playing Catan! (or Monopoly)");
Console.WriteLine("Please limit your dice to d4, d6, d8, d10, d12, d20");
Console.WriteLine("To add a die, type \"add xdy\" to add x number of y sided dice.");
Console.WriteLine("To remove a die, type \"remove xdy.\" to remove x number of y sided dice.");
Console.WriteLine("Type \"dice\" to see a list of all the dice in the pile.");
Console.WriteLine("Type \"roll\" to roll all the dice and see the results!");
Console.WriteLine("Type \"clear\" to clear all the dice and start agin!");
Console.WriteLine("Type \"exit\" to exit program\n");
PlayDice();
Console.ReadKey();
}
static void PlayDice()
{
do
{
string[] xDy = null;
int numberOfDice = 1;
int numberOfSides=1;
Console.WriteLine("\nEnter your command:");
string option = Console.ReadLine();
option = option.ToLower().Trim();
string[] words = option.Split(' ');
string command = words[0];
//CheckCommand(command);
if (words.Length > 1)
{
xDy = words[1].Split('d');
numberOfDice = int.Parse(xDy[0]);
numberOfSides = int.Parse(xDy[1]);
}
ManyDice die = new ManyDice();
if (command == "exit")
{
Console.WriteLine("Thank you, play again, soon!");
break;
}
else if (command == "add")
{
//numberOfSides=CheckDice(numberOfSides);
die.AddDie(numberOfDice, numberOfSides);
Console.WriteLine("You have {0}ed {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "remove")
{
Console.WriteLine("You have {0}d {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "dice")
{
Console.WriteLine("These are your dice:");
die.Display();
}
else if (command == "roll")
{
Console.WriteLine("Here is your roll:");
}
else if (command == "clear")
{
Console.WriteLine("All dice have been cleared.");
}
} while (true);
}
static int CheckDice(int sides)
{
List<int> check = new List<int> {4,6,8,10,12,20};
while (!check.Contains(sides))
{
Console.WriteLine("{0}-sided dice are not available.\nPlease enter 4,6,8,10,12 or 20");
sides = int.Parse(Console.ReadLine());
}
return sides;
}
static string CheckCommand(string instructions)
{
List<string> check = new List<string> { "add", "remove", "dice", "roll","clear", "exit" };
while (!check.Contains(instructions))
{
Console.WriteLine("Command not recognized.\nPlease enter \"add\", \"remove\", \"dice\", \"roll\",\"clear\", or \"exit\"");
instructions = Console.ReadLine();
}
return instructions;
}
}
New Answer based on comments and updated question:
The line ManyDice die = new ManyDice(); is wiping your dice list clean every loop through your program. It's replacing your variable with a new instance of the class, with a fresh list and all.
Simply move that line before the start of the loop:
before the line do {
and then every iteration will use the same instance of ManyDice, and will all share the variable die, without overwriting it.
OLD ANSWER: From what I can see, your program only runs once. And then you need to start it again to put in another dice. Your main function only asks for input once. Whenever you start the program again, all the memory used in the program gets cleared. Unless I’m missing something, that is why your list continues to be reset. You’re actually running a completely new program the next time you try to add dice. So it has no knowledge of the previous runs.
One solution is to say (pseudo code)
While (running) {
// what you have now
if (option == “done”) running = false;
if (option == “roll”) // roll all dice.
}
This will keep prompting the user for commands until they type done. And it remains the same program so that you don’t lose the data from earlier commands.
Update based on comment: you’re recreating the ManyDice instance on each iteration, effectively starting from scratch. Save the instance outside the while loop and then reuse it.
Hint:
Your rolling should probably be done by manyDice.RollAll() And maybe should return a List of RollResults.

Validation Returns False, Then Continues Program Regardless [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Edit add: The problem I was given amounts to making use of a text file that contains 18 differing account numbers. I'm given the option of making the program read it to an array or a List<>. Then the program should allow a user to input a number and determine if it matches an entity in the array/List<>, displaying that it's valid/invalid.
It took me a fair while to get my code to work correctly. Now, I don't mind that a bad input validation returning false is followed by the latter methods being run through, thus producing the second popup. It's rather annoying at times, however. It works fine, like I said, but I'd like to find out if there's a way to make it stop running through the rest if the validation returns false.
private void ReadAccNums(int[] accountNumArray)
{
// Try-catch to prevent file error issues.
try
{
// Increment num var.
int num = 0;
// Open ChargeAccounts.txt file.
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
// Read account numbers into array.
while (num < accountNumArray.Length && !accNumsFile.EndOfStream)
{
// Put each item into accountNumArray.
accountNumArray[num] = int.Parse(accNumsFile.ReadLine());
num++;
}
// Close file.
accNumsFile.Close();
}
catch (Exception ex)
{
// Display error message.
MessageBox.Show(ex.Message);
}
}
// Method to handle TextBox input
// validation.
private bool InputIsValid(ref int accNum)
{
// Flag to make sure input is good.
bool inputValid = false;
// Get and validate accountNumbersAccessTextBox input.
if (int.TryParse(accountNumberAccessTextBox.Text, out accNum))
{
// Did we get this far? Confirm input validation.
inputValid = true;
}
// Display error message for accNum.
else
{
MessageBox.Show("Please input a non-decimal, seven digit number" +
" for the account number.");
// Reset Focus to accountNumbersAccessTextBox.
accountNumberAccessTextBox.Focus();
}
// Return result.
return inputValid;
}
// Method to find out if input
// has a match in ChargeAccounts.txt.
private int AccNumSearch(int accNum,
int[] accountNumArray)
{
// Bool flag for matching accNum.
bool accNumFound = false;
// Index var.
int num = 0;
// Position of Sequential Search.
int position = -1;
// Get input from TextBox.
if (InputIsValid(ref accNum))
{
// Read through array to find
// matching accNum.
while (!accNumFound && num < accountNumArray.Length)
{
if (accountNumArray[num] == accNum)
{
// Found a match? Yay! Access granted!
accNumFound = true;
position = num;
}
num++;
}
}
// Return.
return position;
}
// Method to determine whether input
// matches an account number.
private bool AccNumMatch(int[] accountNumArray,
ref int accNum)
{
// Bool flag to confirm
// matching accNum.
bool accNumMatch = false;
// Got a match? Tell the user.
if (AccNumSearch(accNum, accountNumArray) != -1)
{
accNumMatch = true;
MessageBox.Show("Account number correct. Access granted.");
}
else
{
// No match? Alas.
MessageBox.Show("Account number invalid. Access denied.");
}
// Return.
return accNumMatch;
}
private void accountNumberAccessButton_Click(object sender, EventArgs e)
{
// Declare array to be filled by
// ReadAccNums method.
const int SIZE = 18;
int[] accountNumArray = new int[SIZE];
// Get the account numbers.
ReadAccNums(accountNumArray);
// Var for accNum to ref.
int accNum = 0;
// Is our account number correct?
AccNumMatch(accountNumArray, ref accNum);
}
Your code seems and incredibly verbose approach to:
the user types a number into a textbox
the program checks it's numeric
the program checks it's present in a file
If I was tasked to write such a code I might:
void Login_Click(object sender, EventArgs e){
if(!int.TryParse(accountNumberTextbox.Text, out int seeking)) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
accNumMatch = File.ReadLines("c:\\temp\\accountnumbers.txt").Any(line => line == accountNumberTextbox.Text));
if(accNumMatch) {
MessageBox.Show("Account number correct. Access granted.");
}
else {
MessageBox.Show("Account number invalid. Access denied.");
}
}
because there simply isn't any point in converting the file contents to number and then searching the number; simpler to leave them as strings and compare strings, after making sure what the user entered was a number
And if I used a numericupdown so the user couldn't even enter a non number:
void Login_Click(object sender, EventArgs e){
accNumMatch = File.ReadLines("c:\\temp\\accountnumbers.txt").Any(line => line == accountNumberNumericUpDown.Value.ToString()));
if(accNumMatch) {
MessageBox.Show("Account number correct. Access granted.");
}
else {
MessageBox.Show("Account number invalid. Access denied.");
}
}
YOu can just convert what they entered to text and launch straight into reading the file and looking for a line bearing what they entered
I appreciate you might be learning, so using LINQ is a bit of a cheat, but even so:
void Login_Click(object sender, EventArgs e){
if(!int.TryParse(accountNumberTextbox.Text, out int seeking)) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
accNumMatch = false;
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
while (!accNumsFile.EndOfStream && !accNumMatch)
{
string line = accNumsFile.ReadLine();
accNumMatch = (line == accountNumberTextbox.Text);
}
}
I'll forego lecturing about using/making sure you close and dispose your file readers etc for now ;)
If you have to read a file into an array, you can use System.IO.File.ReadAllLines() as a quick way to read a file. I won't use it here, but you can look it up if you want to see
If you have to read up to X lines from a file, into an array of ints, and then see if any of the ints are the one you seek:
void Login_Click(object sender, EventArgs e){
bool validInput = int.TryParse(accountNumberTextbox.Text, out int seeking);
if(!validInput) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
int[] numbers = new int[100];
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
for(int i = 0; i < numbers.Length && !accNumsFile.EndOfStream; i++)
{
string line = accNumsFile.ReadLine();
numbers[i] = int.Parse(line);
}
accNumMatch = false;
foreach(int number in numbers){
if(number == seeking) { //seeking comes from earlier
accNumMatch = true;
break;
}
}
}
You could break these into separate methods. Make a method that takes an input and gives an output:
void Login_Click(object sender, EventArgs e){
int seek = ConvertToAccountNumber(accountNumberTextbox.Text);
if(seek == -1){
MessageBox.Show("Enter a valid number");
return
}
int[] numbers = GetAccountNumbersInFile("ChargeAccounts.txt");
accNumMatch = ArrayContainsNumber(numbers, seek);
}
//this is basically a variation of int.Parse/int.TryParse
public int ConvertToAccountNumber(string s){
bool validInput = int.TryParse(accountNumberTextbox.Text, out int seeking);
if(!validInput)
return -1; //we will use -1 to signify invalid input, because no account number is ever -1
else
return seeking;
}
//File.ReadAllLines can help with this, as can LINQ Select/int parse
public int[] GetAccountNumbersInFile(string p){
int[] numbers = new int[100];
StreamReader accNumsFile = File.OpenText(p);
for(int i = 0; i < numbers.Length && !accNumsFile.EndOfStream; i++)
{
string line = accNumsFile.ReadLine();
numbers[i] = int.Parse(line);
}
}
//there exist helper methods for doing this too, look at the Array class - https://learn.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1
public bool ArrayContainsNumber(int[] array, int seeking){
foreach(int number in numbers){
if(number == seeking) {
return true;
}
}
return false;
}
I know why you used ref but you should avoid it. Actually the framework uses out when it parses text to a number and returns a boolean to indiccate the success and a number, but you can easily take the approach that something like string.IndexOf takes - it returns -1 if the needle is not found in the haystack. You haven't learned about exceptions yet (probably) but this would be an opportunity to use them too - throw an exception instead of returning a value if the input data is bad
All in, it's one of the few places where out might be reasonable in your career, so use it if you must (for academicc reasons, but don't use ref - ref is for methods that take a variable in with the intention of using its value before possibly overwriting it with something else. This is an out scenario, where the input variable shouldn't have a value and will be overwritten by the method) but

How to use functions step by step

Sorry for the strange title, I just don't know how to name this question.
So I have such a function say().
void say(string printedText) {
gameText.text = printedText;
}
And I need to use it several times. Something like this:
say("test text 1");
say("test text 2");
say("test text 3");
...
I need to change text by clicking Space button. Of course I need to use something like this:
if(Input.GetKeyDown(KeyCode.Space)) {
...
}
But I can't understand how to show text step by step. So for example if I click Space button once I should see "test text 1". Next click should show me "test text 2" etc.
How can I realise it? Thanks in advance.
Depending on your needs you could store different texts in a List<string> or maybe even Queue<string> and do
List example
// Add your texts in the editor or by calling texts.Add(someNewString)
public List<string> texts = new List<string>();
private int index = 0;
if(Input.GetKeyDown(KeyCode.Space))
{
// have a safety check if the counter is still within
// valid index values
if(texts.Count > index) say(texts[index]);
// increase index by 1
index++;
}
Array example
Basically the same as the List<string> but you can't add or remove elements "on the fly" (at least not that simple)
public string[] texts;
private int index = 0;
if(Input.GetKeyDown(KeyCode.Space))
{
// have a safety check if the counter is still within
// valid index values
if(texts.Length > index) say(texts[index]);
// increase index by 1
index++;
}
Queue example
public Queue<string> texts = new Queue<string>();
for adding a new text to the end of the queue do
texts.Enqueue(someNewString);
and then
if(Input.GetKeyDown(KeyCode.Space))
{
// retrieves the first entry in the queue and at the same time
// removes it from the queue
if(texts.Count > 0) say(texts.Dequeue());
}
Simple counter
If it is really just about having a different int value then yes simply use a field
private int index;
if(Input.GetKeyDown(KeyCode.Space))
{
// uses string interpolation to replace {0} by the value of index
say($"test text {0}", index);
// increase index by one
index++;
}
define a class field like this:
int count = 0;
and now everytime space is hit:
if(Input.GetKeyDown(KeyCode.Space)) {
say("test text " + count);
count = count + 1;
}
This Code:
if(Input.GetKeyDown(KeyCode.Space)) {
...
}
only works for Unity, In Visual Studio you'll have to create an Event to whatever object you want to do this, for example, if you want to call a void each time you press spacebar youll have to do this, it is easy: (Image below)
In the propieties window press the bolt icon and after double click on the event you want to create (samples): TextChanged, LocationChnaged, MouseMove, etc...
I will use KeyDown on the TextBox object
image
Now in your code this void should be generated
image
Inside this void i writed the code and this is how it looks:
(put int n = 1 before voids)
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Space)
{
//int n = 1; must be defined
textBox1.Text = "test text " + n;
n++;
}
}
Now each time you'll press or stay pressed spacebar the textbox will be filled with "test text " and the value will be 1 more each time.

Logic trouble with loop

I am creating a windows form that is a random number guessing game. I've made these before in C++ and never had an issue, however I have a big one here- I have no idea how to get the user back to input a number after the loop has began running. Here is my code:
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = 0;
int count = 0;
int accumulator = 0; // accumulator
Random rand = new Random();
int number = rand.Next(1, 100);
txtAnswer.Focus();
while (guess != number)
{
guess = int.Parse(txtAnswer.Text);
if (guess < number)
{
MessageBox.Show("Too Low! Guess again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else if (guess > number)
{
MessageBox.Show("Too High! Try again!");
txtAnswer.Text = "";
txtAnswer.Focus();
count++;
accumulator++;
}
else
{
MessageBox.Show("Correct! you guessed the number in " + accumulator + " tries!");
break;
}
}
}
}
}
I just filled the while loop arguments with something for you guys, even though i know it won't work. Basically, I need to run the loop, get feedback (if the users guess was too high or low) then get the user to be able to input another number BEFORE the loop runs again. I don't know how to get that to happen with a text box control which is where the input will be. Any ideas?
You should not loop inside in the btnGuess_Click. Instead you need to store the state (the number, count, and the accumulator variables) in the scope of the form itself.
Initialize the random number when the form loads, or using some kind of start button.
Then inside the guess button handler, read the text box value and compare it to the number variable, such as what you are doing currently.
What you are building is more a console style application. So there is 1 main loop that is executing all the code.
In forms applications it is an event driven environment. So the user gets a form, presses a button, the form is evaluated and then the method handling ends.
So you have on a class level some variables for counts, in the constructor you add the initialization and the method for submit will be something like
private void btnGuess_Click(object sender, EventArgs e)
{
//Increment counters
//Check
//Show feedback
//Leave the button click code
}
For some more info, check this out:
https://msdn.microsoft.com/en-us/library/dd492132.aspx

random number generator to be displayed on a text box

I'm kind of stuck on a thing I'm working on.. I have a windows form application with different buttons, and each button is supposed to do different thing. Now my problem:
On one button, when I press it, it should generate random numbers (0-1000 for example) and display the number in a textbox, which I also have on the program. I tried to do this code on the button:
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random(); int tal;
tal = slumpGenerator.Next();
}
But unfortunately, no number is displayed on the text box. And i think it could be because I haven't referred that the numbers should display on my textbox, any ideas?
Well sure - you're not setting any properties on your text box. You're ignoring your newly-generated random number. You'd need something like:
Random slumpGenerator = new Random();
// Or whatever limits you want... Next() returns a double
int tal = slumpGenerator.Next(0, 100);
textBox.Text = tal.ToString();
Note that in general it's a bad idea to create many Random instances - but it's not as simple as making it a static variable... see my article on randomness for more details. Also note how I've changed the code to declare a variable and assign it a value in a single statement - that's generally preferable to declaring in one statement and then assigning it a value later.
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random();
int tal = slumpGenerator.Next(0, 1000);
txtBxName.Text = tal.ToString();
}
You need to add a miniumum and maximum to "Random" .Next() method.
You are not setting the textboxes text value anywhere.
You can consider RNGCryptoServiceProvider thread safe class (System.Security.Cryptography namespace) which is cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider.
Implementation is a bit more difficult than using System.Random class.
Sample implementation is as follows:
using System.Security.Cryptography;
...
private RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
private int NextInt32(int maxValue)
{
byte[] intBytes = new byte[4];
rnd.GetBytes(intBytes);
return Math.Abs(BitConverter.ToInt32(intBytes, 0)) % maxValue + 1;
}
// And your method with textBox
private void button5_Click(object sender, EventArgs e)
{
textBox.Text = NextInt32(1000).ToString();
}
You can read more on RNGCryptoServiceProvider in SO question: Pros and cons of RNGCryptoServiceProvider
You need to add a few things to your code. Here is the fulll code for what you want...
private void button5_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random(); int tal;
tal = slumpGenerator.Next(0, 1000);
textBox.Text = tal.ToString();
}
You have to set a minimum and a maximun value you want it to generate. You also have to put the minimum value 1 below what you really want to generate. i.e. if you want to generate a number between 10 and 20, you would need to put the minimum value to 9, and maximum value to 20.
You also need to put the value into a textbox, etc, to show it. Since it is an int, and textbox's text is in a String format, you will need to convert it to a String by putting this at the end of your code: .ToString()
I know this answer is late, but it might be able to help you later!
**Random Number Generation in C#.Net**
Add two namespaces before you write the code
*using System.Security;
using System.Security.Cryptography;*
Code:
Copy and place the following code inside the button
RNGCryptoServiceProvider xx = new RNGCryptoServiceProvider();
byte [] random_number=new byte [512];
xx.GetBytes(random_number);
foreach (var i in random_number)
{
textBox1.Text = i.ToString();
}
for further details in c#.net refer my blogspot : mbthangamalai.blogspot.in

Categories

Resources