i am making a windows form app in c#, I have a for loop which prints 20 elements with a random number between 0 and 500. With this numbers i need to calculate the next numbers. I want to use the variable "numbers[i]" to print it but this doesnt work and the program picks new random numbers. Here is some code:
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
var text = "";
for (int i = 0; i < numbers.Length; i )
{
numbers[i] = random.Next(501);
beforeLoop.Text = $"Element {i} = {numbers[i]} \n";
total = numbers[i];
}
}
private void compare_Click(object sender, EventArgs e)
{
int count = 0;
count ;
if (count ==1 ) // knop is maar 1 keer drukbaar
{
compare.Enabled = false;
}
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i )
{
numbers[i] = random.Next(501);
int numberBigger = numbers[i] 10;
int numberSmaller = numbers[i] - 5;
total = numbers[i];
int number = int.Parse(numberBox.Text);
if (number > numbers[i])
{
printLabel.Text = $"Element {i} = {numberBigger}\n";
}
else
{
printLabel.Text = $"Element {i} = {numberSmaller}\n";
}
}
CodePudding user response:
You create a new array each time: int[] numbers = new int[numberOfItems];
But numbers
should be persistent throughout the life of the app.
public partial class Form1 : Form
{
// Class fields exist through out the life time of the class object
int[] numbers;
int numberOfItems = 20;
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
// Create the array and fill with random nums ONCE
numbers = new int[numberOfItems];
Random random = new Random();
for (int i = 0; i < numbers.Length; i )
{
numbers[i] = random.Next(501);
beforeLoop.Text = $"Element {i} = {numbers[i]}{Environment.NewLine}";
}
}
private void compare_Click(object sender, EventArgs e)
{
compare.Enabled = false;
int number = int.Parse(numberBox.Text);
for (int i = 0; i < numbers.Length; i )
{
if (number <= numbers[i])
{
numbers[i] = 10;
}
else
{
numbers[i] -= 5;
}
printLabel.Text = $"Element {i} = {numbers[i]}{Environment.NewLine}";
}
}
}