Random r = new Random();
int sayi = r.Next(1, 49);
textBox1.Text = sayi.ToString();
This code shows the first random number in textbox1, but I also need to get the output for the other textboxes as well:
(first click)--->Textbox1: 3
(second click)--->textbox2: 24
(third click)---> textbox3: 32
// Declare Click Counter Global
private int clickCounter = 0;
// On Button Click Event
Random r = new Random();
if(clickCounter == 0)
{
textBox1.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
if(clickCounter == 1)
{
textBox2.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
if(clickCounter == 2)
{
textBox3.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
This code block gives you what you want.
If you just have text boxes on your form (so that they are effectively fields in your Form class), you can add an int counter field to your class, initialize it to 0, and have (note: untested code):
Random r = new Random();
int sayi = r.Next(1, 49);
string textBoxName = "textBox"+counter;
FieldInfo fi = GetType().GetField(textBoxName);
TextBox currentTextBox = (TextBox)fi.GetValue();
currentTextBox.Text = sayi.ToString();
couter++;
plese note that this approach is rather ugly. It would be nicer to have these text boxes in a list or array and find them using the index instead of using the name of the field.
Related
I want to check if there is same value in the array or not as I mentioned in the title. And if there is, I want to pass that value and check another random value to add to listbox.
In my form, there is 2 textBox, 1 listbox and 1 button. When button is clicked, listbox has to show random numbers up to sum of textbox1 and textbox2. For instance;
5 entered from textbox1 and 10 entered from textbox2. Sum is of course 15 and listbox has to show 15 random numbers but those numbers have to be different from each other.
I wrote something like that and used Contains method to check if there is same value or not. But the program froze and didn't give any error.
int a, b;
Random rnd = new Random();
int[] array;
private void button1_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
int c = a + b;
array = new int[c];
for (int i = 0; i < array.Length; i++)
{
int number = rnd.Next(c);
foreach(int numbers in array)
{
if (array.Contains(numbers))
{
i--;
}
else
{
array[i] = number;
listBox1.Items.Add(array[i]);
}
}
}
I also did it without foreach(Only Contains part I mean). Also didn't work. I wrote in "else";
array[i] += number;
it also didn't work.
I would be very appreciated if you help me. Thanks in advance.
instead of a for loop, use a while loop:
int = 0;
while(i<c)
{
int random rnd.Next(c);
if(!array.Contains(random))
array[i++] = random;
}
you may also create a list of numbers from 1-15 and then shuffle them (as your random function will create only random numbers from 1-15 just random):
array = Enumberable.Range(0,c).OrderBy(x => rnd.Next()).ToArray();
The above code is much faster, because imagine that we have generated 14 random numbers and only one number (5 for instance) left, it has to go through loop several times so that finally random number that is generated equals to 5, but in the above code there is no need to check that, we just have all numbers and then we shuffle it.
You can try to use do...while instead of for loop
Random.Next get the value from 0 to c - 1, so rnd.Next(c + 1); need to add 1 otherwise, the loop will not be stopped.
var array = new int[c];
int number;
for (int i = 0; i < array.Length; i++)
{
do
{
number = rnd.Next(c + 1);
} while (array.Contains(number));
array[i] = number;
listBox1.Items.Add(array[i]);
}
You basically need to shuffle your data. Create a collection with all values:
var temp = Enumerable.Range(0, c);
Now order it by random
temp = temp.OrderBy(_ => rnd.Next());
Now you can add temp to your listBox
Or, as single line:
listBox1.Items.AddRange(Enumerable.Range(0, c).OrderBy(_ => rnd.Next()));
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);
I want to make button array that include string and integer. I have 30 buttons and named B1, B2, ...., B30 and I want to change their color depend on the counter value. How can I do that? These are what I have done and I stuck
for(Cnt = 0; cnt < 30; cnt++)
{
Button[] Tombol = new Button[]{"B"+(cnt+1)};
Tombol[cnt].BackColor = Color.Red
}
The Control (custom) initialization in the Form (in your case, the Control being a Button) requires more than a simple declaration. Apart from giving name (which you do), two other important things to do are:
To add it to the Control parent
To locate it nicely
Thus, adding those considerations to the Button you are to create, you could do something like this
int noOfBtns = 30;
Button[] Tombols = new Button[30]; //actually, you may not need this at all
for (int cnt = 0; cnt < numOfBtns; cnt++)
{
Button tombol = new Button();
tombol.BackColor = Color.Red;
tombol.Location = new Point(5, cnt * 25); //Read (2) please formulate this more properly in your case
tombol.Name = "B" + (cnt + 1).ToString();
// others like size (maybe important depending on your need), color, etc
this.Controls.Add(tombol); //Read (1) this refers to the `Form` if the parent control you want to put your button to is `Form`. But change the `this` as you see fit
Tombols[cnt] = tombol; //again, actually you may not need this at all
}
Take care of how you formulate the location of your button, very important. The example I gave above is really simple formulation, which might not fit if your number of buttons grow large. But that gives you the basic idea on how important it is to set the location of the Button right.
You may need the array of Button at all, unless for some reason you want to list it. But even you want to list it, you should use List and List.Add instead of Array.
I suggest using Linq to generate the array:
Button[] Tombol = Enumerable
.Range(0, 30)
.Select(i => new Button() {
Text = String.Format("B{0}", i + 1),
BackColor = Color.Red,
//TODO: compute desired color as function of "i" like
// BackColor = Color.FromArgb(i * 8, 255 - i * 8, 128),
//TODO: assign Parent, Location, Size etc. like this:
// Parent = this,
// Location = new Point(10 + 40 * i, 10),
// Size = new Size(35, 20),
})
.ToArray();
I mean like this:
Button[] Tombol = new Button[30];
for(cnt = 0; cnt < 30; cnt++)
{
Tombol[cnt] = new Button
{
Text = "B" + (cnt+1),
BackColor = Color.Red
};
}
First you create the array and in the for loop you instantiate the actual buttons one by one.
You have to initialize the button array first
int numOfBtns = 30;
Button[] Tombol = new Button[numOfBtns];
and after you can fill required items
for (int cnt = 0; cnt < numOfBtns; cnt++)
{
// Name, Content, Foreground .. whatever
Tombol[cnt].Name = "B" + (cnt + 1);
}
At the moment you are recreating your array on each loop of your code rather than creating the array outside of the loop and then adding buttons to it in the loop.
In addition all your buttons are being created in the same position, so they are on top of each other meaning you can only see one of them.
Try something like this, based on a modified version of the code from this previous answer which creates the buttons, adds them to a list you can search and the sets the positions of the buttons too:
int top = 50;
int left = 100;
var buttons = new Dictionary<string, Button>();
for (int i = 0; i < 30; i++)
{
Button button = new Button();
buttons.Add("B"+i, button);
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
button.BackColor = Color.Red;
}
You can then refer to an individual button later with the code:
buttons["B3"].BackColor= Color.Green;
I'm playing with stuff here and am having trouble with something.
I have an input; it can be either a number or a letter. I have to check whether it's a number or a letter. So I used an if for that. If the input is a number, my code should create an int. If it's a letter, it should create a different int. But I can't use the integer later on for some reason. Any way to solve that?
Console.WriteLine("Length (ms)");
string I = Console.ReadLine();
int I2 = Int32.Parse(I);
Console.WriteLine("Height: r for random");
string L = Console.ReadLine();
//So it asks for an input,for which I here want to check what it is
if (L != "r")
{
int He = Int32.Parse(L);
}
else
{
Random Hi = new Random();
int He = Hi.Next(1, 50);
}
//----------------------I want to use the ints in here
while(true)
{
Random R = new Random();
Random R2 = new Random();
int H = R2.Next(1,He);
int rH = H * 100;
Console.WriteLine("Height is {0}",H);
Console.Beep(rH,I2);
You need to adjust the scope of int He to take it outside of the conditional blocks.
int He;
if (L != "r")
{
He = Int32.Parse(L);
}
else
{
Random Hi = new Random();
He = Hi.Next(1, 50);
}
You could also use the conditional operator in this example to make the code look like which might be preferable as a matter of style.
int He = L != "r" ? Int32.Parse(L) : (new Random()).Next(1, 50);
One thing that is notable, about both the above, versions is that Int32.Parse could raise a number of exceptions based on the format of the string L which you probably want to handle either using try - catch statements or by using the TryParse method
I am trying to replace random number with pictures. for example If random number is 1 show picture black.jpg:
Cache[diceKey] = r.Next(1, 5); // random (1-4)
if (r.Next(1, 2) == 1 )
image.BackImageUrl = "Images/black.png";
is there any solutions that I can show my picture if random number is 1?
Store your image urls in an array. Generate a random index to access the image:
string[] imageUrls = new [] { "foo.png", "bar.png", "foobar.png" };
// ...
Random r = new Random();
image.BackImageUrl = imageUrls[r.Next(imageUrls.Length)];
Update (still not getting the issue, though)
Only set a certain image if the generated random number is 1:
int i = r.Next(1, 5); // random (1-4)
Cache[diceKey] = i;
if (i == 1)
{
image.BackImageUrl = "Images/black.png";
}
As I already said in my comment r.Next(1, 2) will always return 1, so you will always show that black image...
I think you should change your code to this:
var randomValue = r.Next(1, 5); // random (1-4)
Cache[diceKey] = randomValue;
if (randomValue == 1)
image.BackImageUrl = "Images/black.png";
else
image.BackImageUrl = "";