ASP.Net Random Generator Using A List - c#

I am trying to code a random generator using a list in the code behind. I am able to get a fully working number generator using the code below but I now want the generator to run through a list of places and not numbers but I'm stuck with it as I am completely new to developing.
Code for random number generator
private void btnGenerate_Click(object sender, EventArgs e)
{
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
As I said I want my generator to use places to eat (for example) but I am stuck
private void btnGenerate_Click(object sender, EventArgs e)
{
Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
I tired commenting out the int Places = Place.Next(); and changing txtResult.Text = Places.ToString(); to txtResult.Text = Eat.ToString(); but this causes the following error to display in the field on my application when I click the 'Generate' button
System.Collections.Generic.List`1[System.String]

Try this:
List<string> Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtResult.Text = Eat[Places];
The line int Places = Place.Next(0, Eat.Count);
will generate a random number within the range 0 to Eat.Count - 1.
This will produce a valid index within your list. Then Eat[Places]accesses
the randoly chosen string.

Related

whats wrong with my code? i just started with C# and i dont know whats going on [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I just started coding with C# and i keep getting this error 'Index was outside the bounds of the array.' and i dont know what i did wrong anyone able to help? I keep getting this message
Index was outside the bounds of the array.
I tried looking around but didnt find anything.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ChromeDriver driver = new ChromeDriver(#"C:\webdrivers");
//textbox input
// string quest = question1.Text;
//random choise
var random = new Random();
var Names = question1.Text.Split();
int index = random.Next();
//the error is here\\
string randomName = Names[index];
driver.FindElement(By.ClassName("whsOnd")).SendKeys(randomName);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ChromeDriver driver = new ChromeDriver(#"C:\webdrivers");
ChromeDriver drv; Thread th;
string url = "google.com";
driver.Navigate().GoToUrl(url);
}
}
"Index was outside the bounds of the array" suggests that the random index generated is larger than the size of your Names array

Random number generator Issue

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

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

Passing arrays to a method inside event C#

Im trying to create a section of a program, where a user presses a button and a image is placed in one of 9 pictureboxes. Each time the button is clicked, a different picturebox should be selected. However, before i get to that, i'm having trouble getting my method to see the arrays i am trying to pass it.
I have 2 arrays, Slots and SlotsUsed and i am trying to initalise them when the program starts. However, when i try to pass them to the method "randomBox" which is called within "Button1" visual studio says they do not exist. How can i make these arrays visible throughout my code?
Many thanks
Anthony
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pin_program
{
public partial class Mainscreen : Form
{
//Sets where users files are to be stored (for later use)
string activeDir = #"C:\Users\Tony\Downloads\Programs\pin program\Users";
public Mainscreen()
{
InitializeComponent();
}
//method to generate random number
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public void randomBox(int pictureVal, PictureBox[] Slots, bool[] SlotsUsed)
{
//generate random number
int j = RandomNumber(0, 9);
if (SlotsUsed[j] == false)
{
// Create image, assign it and set slots value to used
Image newImage = Image.FromFile(#"C:\Users\Tony\Downloads\Programs\pin program\pin program\pin program\Images\" + pictureVal + ".jpg");
Slots[j].Image = newImage;
SlotsUsed[j] = true;
}
else
do
{
j = RandomNumber(0, 9);
} while (SlotsUsed[j] == false);
return;
}
private void button1_Click(object sender, EventArgs e)
{
//for use later
string userName = textBox1.Text;
//for use later
label1.Visible = true;
//test call of method.
randomBox(1, Slots, SlotsUsed);
}
public void Mainscreen_Load(object sender, EventArgs e)
{
//array for slots
PictureBox[] Slots = new PictureBox[9];
Slots[0] = pictureBox1;
Slots[1] = pictureBox2;
Slots[2] = pictureBox3;
Slots[3] = pictureBox4;
Slots[4] = pictureBox5;
Slots[5] = pictureBox6;
Slots[6] = pictureBox7;
Slots[7] = pictureBox8;
Slots[8] = pictureBox9;
//array for used slots
bool[] SlotsUsed = new bool[9];
for (int i = 0; i != (SlotsUsed.Length); i++)
{
SlotsUsed[i] = false;
}
}
}
}
EDIT:
I dont seem to be able to post comments for some reason, so i'll just ask here. How would i declare my arrays as instance variables instead of local? Does instance variable have another name i might know it by?
CHeers
Currently you're declaring Slots and SlotsUsed as local variables in Mainscreen_Load. They need to be instance variables in your form, as otherwise you can't refer to them elsewhere - and indeed they won't logically exist elsewhere. They're part of the state of your form, so they should be instance variables.
Additionally, your approach for generating random numbers is broken - see my article on random numbers for more information.
I'd also add that you might consider just using a single collection, shuffling it to start with, and then removing items from it as you go - that way you can easily tell when you've run out of images, and you don't have to loop round until you find an unused slot.
well, the easiest way to do this would be to declare a field.
protected PictureBox[] Slots
inside your Form class (outside of any methods.

Categories

Resources