I have 2 listboxes that i need to put 10 random generated numbers in. Then i need to calculate the sum of listbox 1 and the sum of listbox 2 and compare them to see which one is bigger. I do get different numbers in each listbox but for some reason the sum of the listboxes is always the same. How do i make it that the sum is different per listbox.
this i my code at the moment.
private void btnGo_Click(object sender, EventArgs e)
{
Random random = new Random();
listBox1.Items.Clear();
listBox2.Items.Clear();
for (int i = 0; i < 10; i++)
{
int nummer = random.Next(20);
int nummer2 = random.Next(20);
listBox1.Items.Add(nummer);
listBox2.Items.Add(nummer2);
}
if (addListbox1() > addListbox2())
{
textBox1.Text = "Listbox1 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox1());
listBox1.BackColor = Color.Green;
listBox2.BackColor = Color.Red;
}
else
{
textBox1.Text = "Listbox2 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox2());
listBox1.BackColor = Color.Red;
listBox2.BackColor = Color.Green;
}
}
private int addListbox1()
{
int listbox1total = 0;
for (int k = 0; k < listBox1.Items.Count;)
{
listbox1total += Convert.ToInt32(listBox1.Items[k++]);
}
return listbox1total;
}
private int addListbox2()
{
int listbox2total = 0;
int k = 0;
while(k < listBox2.Items.Count)
{
listbox2total += Convert.ToInt32(listBox1.Items[k++]);
}
return listbox2total;
}
You have a typo (an old story of copy + paste) in the code:
listbox2total += Convert.ToInt32(listBox1.Items[k++]);
should be
// please, notice "listBox2.Items"
listbox2total += Convert.ToInt32(listBox2.Items[k++]);
i.e. listbox2total should be the sum of listBox2.Items.
In order to avoid such errors, change the design, do not copy yourself, extract methods:
// Easiest, but not thread safe
private static Random random = new Random();
private static void FillBox(ListBox box, int count = 10) {
box.Items.Clear();
box.Items.AddRange(Enumerable
.Range(0, count)
.Select(x => (Object) random.Next(20))
.ToArray());
}
private static int SumBox(ListBox box) {
return box.Items
.OfType<Object>()
.Sum(x => Convert.ToInt32(x));
}
...
FillBox(listBox1);
FillBox(listBox2);
if (SumBox(listBox1) > SumBox(listBox2)) {
...
}
Related
So I'm trying to remove all even numbers from the generated random list I created. But this message keeps showing up: "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I don't know what I'm doing wrong. What do I need to change?
public partial class Form2 : Form
{
ArrayList array = new ArrayList();
int count = -1;
int[] numbers = new int[5];
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random randNum = new Random();
for (int i = 0; i < 5; i++)
{
numbers[i] = randNum.Next(-100, 100);
array.Add(numbers[i]);
richTextBox1.Clear();
}
for (int i = 0; i <= count; i++)
{
//displays random numbers to rich textbox
richTextBox1.AppendText(array[i].ToString() + '\n');
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (int i in array)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Your code in Button2_click is wrong. You are using foreach loop and then trying to access the index of array using its elements value.
change your second button code with following code
for (int i = 0; i < array.Count; )
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
else {
i++;
}
}
foreach (var item in array)
{
richTextBox1.Text = item +"\n";
}
You should change your enumeration like:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < array.Count; i++)
{
if (Convert.ToInt32(array[i]) % 2 == 0)
{
array.RemoveAt(i);
}
richTextBox1.Text = array[i].ToString();
}
}
Using LINQ you can achieve this easily.
var oddArray = array.Where(a => a % 2 != 0);
richTextBox1.Text = string.Join(", ", oddArray);
PS - You just need to add a namespace i.e. System.Linq
I tried everything i could find online and spent a lot of time on this but I cant do it.
It's a form with a ListBox with random numbers from 20 to 30 and I need to find the min and show its position. The hard part is that if i have 2 of the same number or 3 of them, then I don't know what to do and I tried almost everything.
This is the code i did so far:
Random r = new Random();
int[] a;
private void button2_Click(object sender, EventArgs e)
{
int i;
a = new int[10];
listBox1.Items.Clear();
for (i = 0; i < 10; i++)
{
a[i] = r.Next(20, 31);
listBox1.Items.Add(a[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] b;
b = new int[10];
int mini=3435, i,index=0;
b = (int[])a.Clone();
for (i = 1; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
}
}
index = Array.IndexOf(b, mini);
label2.Text = Convert.ToString("la pozitia: " + index);
label1.Text = Convert.ToString("Minimul este: " +mini );
}
This is how it should look:
Since you simply want to output the positions as a comma seperate list, you can use a separate string for the list of positions that match:
int[] b;
b = new int[10];
int mini = int.MaxValue, i, index = 0;
string miniList = "";
b = (int[])a.Clone();
for (i = 0; i < 10; i++)
{
if (b[i] < mini)
{
mini = b[i];
miniList = "";
}
if (b[i] == mini)
{
if (!string.IsNullOrEmpty(miniList))
{
miniList += ", ";
}
miniList += i;
}
}
label1.Text = Convert.ToString("Minimul este: " + mini);
label2.Text = Convert.ToString("la pozitia: " + miniList);
NOTE: I also set the mini value to int.MaxValue to begin with so code should work with any number range
namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;
string[] doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int[] systolic = new int[5];
int[] diastolic = new int[5];
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}
//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;
doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
}
}
}
}
}
This is the file it is getting it from
When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).
I've tried resetting the array at the end of the loop but that solves nothing
Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.
Like this:
string name = inputFile.ReadLine();
//Calculates average for systolic
double total = 0;
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
double average_sys = total / 5;
int doctor = int.Parse(inputFile.ReadLine());
string DocN = doctors[doctor];
listBox1.Items.Add(name + "\t" + average_sys + "\t" + DocN);
Even better, use var instead of setting the variable type in two places and risking getting it wrong.
You're not resetting your variables for total and average for the second set of measurements.
I am working with Round Robin (RR). I am building random Round-Robin value. I get the time for the RR randomly. In the first run it shows me the current values that i have in the list. but when it goes to run for the second time it just say the index is not presented in the dictionary key. I am trying to fix this problem I have add the time and the quantum tim that the algorithm reduce the value from the dictionary and return back to the dictionary it the value is > 0.
Dictionary<int, int> waytosave = new Dictionary<int, int>();
List<int> randomListxCoor = new List<int>();
List<int> randomListyCoor = new List<int>();
int xCoor;
int yCoor;
Random coor = new Random();
Random setTimeRandom = new Random();
int randomTimeSetting;
int NodeIndex = 0;
Graphics graphDraw;
Graphics drawLine;
int TimeToProcess = 0;
string NodeName = "";
int QuantumTime = 1;
int TotalRouterTime = 0;
int NextNodeToProcess = 0;
public Form1()
{
InitializeComponent();
this.graphDraw = this.panel1.CreateGraphics();
this.drawLine = this.panel1.CreateGraphics();
}
private void btnRun_Click(object sender, EventArgs e)
{
int nodesNumber = (int)this.numNodes.Value;
SolidBrush getNodesDrawn = new SolidBrush(Color.LightYellow);
for (int x = 1; x <= nodesNumber; x++)
{
xCoor = coor.Next(0, 700);
yCoor = coor.Next(0, 730);
if (!randomListxCoor.Contains(xCoor))
{
randomListxCoor.Add(xCoor);
}
if (!randomListyCoor.Contains(xCoor))
{
randomListyCoor.Add(yCoor);
}
randomTimeSetting = setTimeRandom.Next(1, 10);
//Draw the line from main Node to the other Nodes
Pen linePen = new Pen(Color.DarkMagenta, 2);
drawLine.DrawLine(linePen, 350, 360, xCoor, yCoor);
drawLine = this.panel1.CreateGraphics();
graphDraw.FillEllipse(getNodesDrawn, xCoor - 5, yCoor - 5, 15, 12);
//Add the values t the Dictionaries and the List.
waytosave.Add(x, randomTimeSetting);
}
}
private void btnRunTIme_Click(object sender, EventArgs e)
{
this.QuantumTime = (int)this.numQuanrum.Value;
this.ComputeTotalNodeTime();
this.timerRoundRobin.Enabled = true;
}
private void timerRoundRobin_Tick(object sender, EventArgs e)
{
this.NodeIndex = this.GetNextNodeToProcess();
if (this.NodeIndex >= 0)
{
this.waytosave[this.NodeIndex] -= this.QuantumTime;
here at this point it getting crashed. I tried to fixed the number of iteration but if i change the number of iterations it will not go through all the values in the dictionary.
if (this.waytosave[this.NodeIndex] < 0)
{
this.waytosave[this.NodeIndex] = 0;
}
this.NodeName = this.NodeIndex.ToString();
this.TimeToProcess = this.waytosave[this.NodeIndex];
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ this.TimeToProcess
+ "Router name: "
+ this.NodeName;
}
else
{
this.timerRoundRobin.Enabled = false;
this.txtOutput.Text += "\r\r\n" + " Ends x " + TotalRouterTime.ToString();
return;
}
}
private int GetNextNodeToProcess()
{
int NextNodeIndex = -1;
if (NextNodeToProcess >= this.waytosave.Count)
{ NextNodeToProcess = 0; }
for (int i = NextNodeToProcess; i < this.waytosave.Count; i++)
{
if (this.waytosave[i] > 0)
{
NextNodeIndex = i;
break;
}
}
NextNodeToProcess++;
return NextNodeIndex;
}
private void ComputeTotalNodeTime()
{
this.TotalRouterTime = 0;
foreach (KeyValuePair<int, int> item in this.waytosave)
{
this.TotalRouterTime += item.Value;
this.txtOutput.Text += "\r\r\n" + " Time Remaining: "
+ item.Value
+ "Router name: "
+ item.Key;
}
}
I am trying to fix this value from days but i have no success. the problem that in cannot read the first value from the dictionary. How can I solve this problem. Can you please give me some Hence.
I am finish up my Dice roll program and have been tweaking it here and there, my program currently allows the user to roll as many times as they would like however, Ive tried using different code in order for the player to be allowed only a certain number of rolls before they get the message that they have lost all their money, for example my game should predetermine a random number lets say 9, after 9 rolls they get the message and I reset everything and game over. im a newb :(
Code from Comment
private void button1_Click(object sender, EventArgs e)
{
rollagainLabel.Visible = true;
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
int maxRolls = rand.Next(5);
for (int i = 0; i < maxRolls; i++)
if (roll1 == 1)
{
diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
Just calculate the number at the start of the program and store it in a variable, then count the number of times the player rolls and check to see if it reaches the previously calculated number.
Random rand = new Random();
int maxRolls = rand.Next(10); // 10, or whatever you want the max possible limit to be
for(int i = 0; i < maxRolls; i++)
{
roll(); // obviously this is not actual code to be used, but it gives you the structure. each roll goes inside this loop.
}
This should do the trick for you, I am checking if the maxRolls is equal to zero then creating a new Random Number, then I am checking if the rollCount is equal to maxRolls and resetting everything if it is.
public partial class Form1 : Form
{
int runningTotal;
int roll1;
int maxRolls;
int rollCount;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (maxRolls == 0)
{
Random getMax = new Random();
rollagainLabel.Visible = false;
maxRolls = getMax.Next(10) ;
}
else
if(rollCount >= maxRolls)
{
maxRolls = 0;
rollagainLabel.Visible = true;
rollCount = 0;
runningTotal = 0;
totalmoneyLabel.Text = "$0.0";
return;
}
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
rollCount += 1;
if (roll1 == 1)
{
//diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
}
I think what you want to do is to generate your random number in the Page_Load event.
After that, save that into the session, so that you can use it in your Button_Click event to compare.
Random rand = new Random();
Session["maxRolls"] = rand.Next(10);
after that, your can retrieve the value this way
int maxRolls = (int)Session["maxRolls"];
edit
Here is a sample code to tie everything together
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int minAllowableRolls = 1;
int maxAllowableRolls = 10;
Random rand = new Random();
Session["maxRolls"] = rand.Next(maxAllowableRolls - minAllowableRolls) + minAllowableRolls;
Session["rollCount"] = 0;
Session["runningTotal"] = 0;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int maxRolls = (int)Session["maxRolls"];
int rollCount = (int)Session["rollCount"];
int runningTotal = (int)Session["runningTotal"];
rollCount++;
if (rollCount < maxRolls)
{
Random rand = new Random();
runningTotal += rand.Next(6) + 1;
Label1.Text = runningTotal.ToString();
}
else
{
// Game has ended
}
Session["rollCount"] = rollCount;
Session["runningTotal"] = runningTotal;
}