Random numbers in C# - c#

I get the error below when I try to run the application I am sure its something simple but I dont see it. What I am trying to do it when I click a button I have labeled Play. I want to call a method called randomnumber. Then I want the results to be displayed in lblPickFive_1.
I have 2x2,Pick5,and powerball. Each random number is to be displayed in its own label I created.
For now I am just looking to get past the one of generating a random number and having it displayed in the one label then I will move onto the rest. And I am sure post more questions if I cant figure out the rest.
Error 1 No overload for method 'RandomNumber' takes '0' arguments
using System;
using System.Windows.Forms;
namespace LotteryTickets
{
public partial class Form1 : Form
{
/// <summary>
/// no-args Constructor
/// </summary>
public Form1()
{
InitializeComponent();
}
#region "== Control Event Handlers =="
private void Form1_Load(object sender, EventArgs e)
{
ClearWinningNumbers();
}
#endregion "== End Control Event Handlers =="
#region "== Methods ==";
/// <summary>
/// Clears the text inside the winning number "balls"
/// </summary>
private void ClearWinningNumbers()
{
this.lblPickFive_1.Text = "";
this.lblPickFive_2.Text = "";
this.lblPickFive_3.Text = "";
this.lblPickFive_4.Text = "";
this.lblPickFive_5.Text = "";
this.lblTwoByTwo_1.Text = "";
this.lblTwoByTwo_2.Text = "";
this.lblPowerball_1.Text = "";
this.lblPowerball_2.Text = "";
this.lblPowerball_3.Text = "";
this.lblPowerball_4.Text = "";
this.lblPowerball_5.Text = "";
this.lblPowerball_PB.Text = "";
}
#endregion "== End Methods ==";
private void cblTwoByTwo_2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cblTwoByTwo_1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
private void lblPickFive_1_Click(object sender, EventArgs e)
{
}
private void RandomNumber(int min, int max)
{
int num = new Random().Next(min, max);
lblPickFive_1.Text = num.ToString();
}
}
}

First, you shouldn't be newing up a random number generator every time you want a new random number. You should set the generator as a static or member variable and refer to it for each new number.
Second, you have to pass a min and a max to your RandomNumber method.

Well, your code doesn't match the error, but look at this:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
private void RandomNumber(int min, int max)
{
int num = new Random().Next(min, max);
lblPickFive_1.Text = num.ToString();
}
RandomNumber has two parameters, min and max. You haven't specified any in the call inside btnPlay_Click. That's what the compiler is complaining about. Change the call to something like:
RandomNumber(5, 10);
Even when that's fixed, you shouldn't create a new instance of Random each time. As it happens, it's unlikely to cause problems in this particular case as it's triggered by a user action, but you should read my article on random numbers to see what the problem is and how to avoid it.

You need to pass in values:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
should be:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber(0, 50000);
}

Your RandomNumber method takes two arguments.
If you want to call the method, you need to pass two arguments.

You're calling RandomNumber(); in btnPlay_Click but the RandomNumber method requires min and max.

Setup one Random object and initialize it once.
class Form1
{
...
Random rnd = new Random();
}
then to use it every time it is needed
void RandomNumber(int min, int max)
{
int num = rnd.Next(min, max);
...
}
What happens everytime you call new() it re-seeds the random number and you may end up with the same numbers over and over. I have had this happend to me and it killed me

Related

I want to create a program that automatically updates the maximum value when I press the button

I'm sorry to ask you a basic question first. It hasn't been long since I learned C#.
private void numberButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int randNumber = rand.Next(1, 1000);
randomNumber.Text = randNumber.ToString();
bestScoreLabel.Text = randomNumber.Text;
}
How can I implement the function so that the maximum value of the bestScoreLabel is automatically updated when I click the number button as shown in the picture above?
Currently, the code is configured as above, but the problem occurs that the maximum and current values are the same output.
The idea is to have a variable to keep tracking the max number.
private static int _maxNumber = 0;
private void numberButton_Click(object sender, EventArgs e){
Random rand = new Random();
int randNumber = rand.Next(1, 1000);
randomNumber.Text = randNumber.ToString();
if (_maxNumber < randNumber)
{
_maxNumber = randNUmber;
}
bestScoreLabel.Text = _maxNumber.ToString();
}

Parsing int does not work for some odd reason

I have a second form that pops up upon clicking a button, a user can input some parameters for a method, save the input within a variable, and then I parse the result to an int ( thus so I can utilize it within my method ). Now, upon parsing it, the value appears to be NULL as oppose to what the user inputted within the textboxes.
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
while (i == 0)
{
if (form.click) // ok button is clicked
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
goto break_0; // break out of loop ( loop is to check when button is clicked )
}
}
}
}
As you can see here, the values that the user inputs is Height,Width and Framerate respectively. It parses it to an int, as I explained, and stores it in the displayproperties int array.
This is the second form:
public string Height { get; set; }
public string Width { get; set; }
public string Framerate { get; set; }
public bool click = false;
public Form2()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e){}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Height = height.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Width = width.Text;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
Framerate = framerate.Text;
}
public void OK_Click(object sender, EventArgs e)
{
click = true;
}
Ultimately, the values are then passed into this class:
public Class1(int width, int height)
However I get an out of range exception saying the value must be greater than zero. Goes without saying, the values I inputted were certainly greater than zero ( 800, 600, 60 respectively ) where 60 is used elsewhere.
Since my comment suggestion worked for you, I'll add it as an answer.
From what you've said, it sounds likely that you're not setting DialogResult anywhere, so your if statement is never being entered because the condition isn't met.
You should set the dialog result and close the form in OK_Click:
public void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
And then you should remove the extra code from your main form:
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
}
}
}
The dialog result will serve as your click property so this is no longer required. By the way, I recommend switching to TryParse instead so that you can actively check if the input values are valid integers, as opposed to leaving it until exceptions are thrown.
An example of this:
string a = "hello"; // substitute user input here
int result;
if (!int.TryParse(a, out result))
{
MessageBox.Show($"{a} isn't a number!");
return;
}
MessageBox.Show($"Your integer is {result}");
If you're newish to programming, I recommend getting familiar with how to use the debugger. Setting a breakpoint and inspecting values as you stepped through the code would have revealed where the problem was very quickly. Microsoft have a tutorial for this.

Random number generator with strings

I have some code that sends a number that is pre-calculated to an Arduino.
instead of a pre-calculated number, I want a random number between a range of number, for example between the numbers 1 to 20, the random number is 18,
after the random number is found put it in a string so I can work with it.
I've tried many things on stack overflow but things are too complicated and I work with C#.
the code below is what I have right now,
I would prefer that it will send that random number to the Arduino
namespace MyLaserTurret
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watch = Stopwatch.StartNew();
port.Open();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
writeToPort(new Point(e.X, e.Y));
}
public void writeToPort(Point coordinates)
{
if (watch.ElapsedMilliseconds > 15)
{
watch = Stopwatch.StartNew();
port.Write(String.Format("X{0}Y{1}",
(coordinates.X / (Size.Width / 180)),
(coordinates.Y / (Size.Height / 180))));
}
}
}
}
To create a random number as a string you use this code
private Random random = new Random();
public string RandomNumber(int min, int max)
{
return random.Next(min, max).ToString();
}
Please note that it is probably best practice to declare a "Random random = new Random();" as a class property because when a Random is created too closely together they will just keep having the same value

How to print an array in forms (C#)

I have a mathematical problem and I´m trying to solve it, the problem is that you have 81 coins, but one is fake and it´s heavier than the others,you have to find out which one is the fake one by using a scale and doing only 4 comparisons.
I´m trying to make it like a game, when a users decides which coin will be the fake one, and the other player has to find it.
I made an array named monedasf and made all the values 0, so when the users type in the coin that wants to be the fake one, the value changes to 1. I´m trying right now to print the array, but I don´t know if I have to print it in a multiline textbox or where, here´s the code I have untill now.
public partial class Form1 : Form
{
public static int[] monedasf = new int[81];
public Form1()
{
InitializeComponent();
for( int i = 0; i<=80;i++)
{
monedasf[i] = 0;
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
monedasf[n] = 1;
textBox1.Clear();
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 80; i++)
textBox2.Text = Convert.ToString(monedasf[i]);
}
}
I have only BASIC KNOWLEDGE of programming, that´s why my code might be so primitive :D
Try using something like this:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 80; i++)
textBox2.Text += monedasf[i].ToString() + " ";
}
If you want you can replace " " with any separator you want, like "\n" for newline.
Actually your code would work too, the problem is you were reseting textBox2's text by using assign operator:
textBox2.Text = Convert.ToString(monedasf[i]); // will clear and then print
textBox2.Text += Convert.ToString(monedasf[i]); // will not clear and print
All you need is not to reset previous text inside.
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = string.Join(", ", monedasf);
}
Use string.Join which is very useful for display.

how to make checkboxes work in accordance with labels c#(yahtzee)

This is my form running, i want to code the checkboxes so that they can hold the picture of their specific dice
Image[] diceImages;
int[] dice;
Random rand;
#endregion
#region Initialization
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
diceImages=new Image[7];
diceImages[0] = Properties.Resources.dice_face_0;
diceImages[1] = Properties.Resources.dice_face_1;
diceImages[2] = Properties.Resources.dice_face_2;
diceImages[3] = Properties.Resources.dice_face_3;
diceImages[4] = Properties.Resources.dice_face_4;
diceImages[5] = Properties.Resources.dice_face_5;
diceImages[6] = Properties.Resources.dice_face_6;
dice = new int[5] { 0, 0, 0, 0, 0 };
rand = new Random();
}
#endregion
private void btnRoll_Click(object sender, EventArgs e)
{
for (int i = 0; i < dice.Length; i++)
dice[i] = rand.Next(1, 7);
Array.Sort(dice);
lblDie1.Image = diceImages[dice[0]];
lblDie2.Image = diceImages[dice[1]];
lblDie3.Image = diceImages[dice[2]];
lblDie4.Image = diceImages[dice[3]];
lblDie5.Image = diceImages[dice[4]];
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void chk4_CheckedChanged(object sender, EventArgs e)
{
}
i have created 5 checkboxes with names chk1-5, i have tried fitting the code in but it doesn't work, could someone help me make this code work.
While your question is pretty unclear as to how you actually want your UI to look like, what might help is the use of UserControls:
You could make a new UserControl named DiceControl that combines one dice image and its corresponding CheckBox. You can then put multiple instances of that control on your form in the designer as if it were just one control. That might help you align stuff the way you want.
All you need to do is create methods/properties on the DiceControl that allow you to get/set the current image and the current hold status.

Categories

Resources