So I have a listbox of salaries. And a button, which if clicked, shows the number of salaries above the average salary amount, and the number below the average salary amount. However, I cannot for the life of me figure out how to form this loop which return the number below and above the avg. salary amount. Here is what I have so far:
double[] employeeSalary = new double[7] { 8500.50, 7005.99, 9123.00, 100123.50, 6550.00, 8123.90, 7500.95 };
public Form2()
{
InitializeComponent();
listBox1.DataSource = employeeSalary;
}
private void button3_Click(object sender, EventArgs e)
{
double avgSalary;
avgSalary = employeeSalary.Average();
for (int i = 0; i < employeeSalary.Length; i++)
{
}
}
You already used LinQ, you can use it for the other tasks, too:
var avgSalary = employeeSalary.Average();
var aboveAverageCount = employeeSalary.Count(x => x > avgSalary);
var belowAverageCount = employeeSalary.Count(x => x < avgSalary);
Related
Hi I'm struggling with this assignment.
When the program starts 4 methods are being executed where the next thing hapens.
One array gets filled with 100 random numbers between 1 and 1000 000 (method1)
The first listbox gets filled with aal the numbers from the array (method2)
The second listbox gets filled with the 5 smalest numbers from the array (method3)
The third listbox gets filled with the 5 biggest numbers from the array (method3)
This has to run when the program starts.
So far my array gets filled and the first listbox gets filled to.
But only in one and not through different methods. I tried to split it up but without success. And my deadline is near.
Sorry for the rookie mistakes btw.
public partial class RandomArray : Form
{
// array met onze 100 waarden
int[] arrRandomNumbers = new int[100];
// random variabele
Random randomGenerator = new Random();
int iRandomNumber = 0;
public RandomArray()
{
InitializeComponent();
AddNumbers();
}
private void AddNumbers()
{
for (int i = 0; i < arrRandomNumbers.Length; i++)
{
iRandomNumber = randomGenerator.Next(1, 1000000);
arrRandomNumbers[i] = iRandomNumber;
}
foreach (var number in arrRandomNumbers)
{
lbxOne.Items.Add(number);
}
}
}
If I understand, you're trying to populate each list in a different function. This is untested but something like this should work:
using System.Linq; //Make sure to add Linq access
public partial class RandomArray : Form
{
// array met onze 100 waarden
int[] arrRandomNumbers = new int[100];
// random variabele
Random randomGenerator = new Random();
int iRandomNumber = 0;
public RandomArray()
{
Console.WriteLine("Creating new RandomArray Class.");
AddNumbers();
PopulateListOne();
PopulateListTwo();
PopulateListThree();
}
private void AddNumbers()
{
for (int i = 0; i < arrRandomNumbers.Length; i++)
{
iRandomNumber = randomGenerator.Next(1, 1000000);
arrRandomNumbers[i] = iRandomNumber;
}
}
private void PopulateListOne() {
Console.WriteLine("All Numbers:");
foreach (var number in arrRandomNumbers)
{
Console.WriteLine(number.ToString());
//lbxOne.Items.Add(number);
}
}
private void PopulateListTwo() {
Console.WriteLine("Top 5 Numbers:");
var top5 = arrRandomNumbers.OrderByDescending(x => x).Take(5).ToArray();
foreach (var number in top5)
{
Console.WriteLine(number.ToString());
//lbxTwo.Items.Add(number);
}
}
private void PopulateListThree() {
Console.WriteLine("Bottom 5 Numbers:");
var bot5 = arrRandomNumbers.OrderBy(x => x).Take(5).ToArray();
foreach (var number in bot5)
{
Console.WriteLine(number.ToString());
//lbxThree.Items.Add(number);
}
}
}
In a fiddle: https://dotnetfiddle.net/h3v6n0
I think you want this:
I suggest the following:
create a data model to hold the data (the number lists).
public class RandomNumberLists
{
static readonly Random rng = new Random();
public RandomNumberLists(int count)
{
Numbers = new int[count];
for (int i = 0; i < Numbers.Length; i++)
{
Numbers[i] = rng.Next(1, 1000000);
}
MinFive = Numbers.OrderBy((x) => x).Take(5).ToArray();
MaxFive = Numbers.OrderByDescending((x) => x).Take(5).ToArray();
}
public int[] Numbers { get; }
public int[] MinFive { get; }
public int[] MaxFive { get; }
}
Use the built-in methods of .OrderBy() and OrderByDescending() to sort the list of random numbers from bottom to top and top to bottom. Then extract the first n-th numbers with the .Take(n) method and finally make a copy with the .ToArray().
Use the listbox .DataSource property to set the items in the listbox for display
public partial class Form1 : Form
{
RandomNumberLists numberLists;
public Form1()
{
InitializeComponent();
numberLists = new RandomNumberLists(100);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
listBox1.DataSource = numberLists.Numbers;
listBox2.DataSource = numberLists.MinFive;
listBox3.DataSource = numberLists.MaxFive;
}
}
Here I initialize the numbers in the form constructor, and assign the lists to the listboxes in the .OnLoad() method which happens before initial display of the form.
I'm trying to have the user input doubles into 4 different textBoxes. Then, once the user clicks the calculate button, the following will happen:
foreach loop runs, parses textbox.Texts to doubles, and then adds
them to a list
for loop runs and indexes through the list, adding
them all up.
List item sum from previous step is divided by the number of values in the list result is entered into another textbox.
When I run it, no errors happen, but the result is not displayed in the texbox. Why is nothing getting displayed?
private void CalculateButton_Click(object sender, EventArgs e)
{
double gpa = 0;
List<double> grades = new List<double>();
foreach(Control textBox in Controls)
{
if ((textBox.GetType().ToString() == "System.Windows.Form.Textbox") && (textBox.Name.Contains("gradeBox")))
{
grades.Add(double.Parse(textBox.Text));
}
}
for(int i =0; i<grades.Count; i++)
{
gpa += grades[i];
}
gpa /= grades.Count;
gpaBox.Text = gpa.ToString();
}
Looks like the namespace of textbox is not quite correct. It should be System.Windows.Forms.TextBox. Notice "s" and capital "B". Following is the corrected version.
private void CalculateButton_Click(object sender, EventArgs e)
{
double gpa = 0;
List<double> grades = new List<double>();
foreach (Control textBox in Controls)
{
if ((textBox.GetType().ToString() == "System.Windows.Forms.TextBox") && (textBox.Name.Contains("gradeBox")))
{
grades.Add(double.Parse(textBox.Text));
}
}
for (int i = 0; i < grades.Count; i++)
{
gpa += grades[i];
}
gpa /= grades.Count;
gpaBox.Text = gpa.ToString();
}
I am writing a program using GUI in C# that includes three text boxes (one for name input, one for grade input and one for grade output), and five buttons (one to take in the name/grade and add to corresponding arrays, one to display just the name and grade that were just entered, one to display lowest grade, one to display highest grade and one to display the class average).
I have the form designed but need help with some of the code, there are two arrays one for the grade and one for name both which have five values initially stored within them. Here is the code I have so far:
namespace WindowsFormsApplication3
{
using static System.Console;
public partial class highestGrade : Form
{
int[] grade = new int[] { 90, 80, 60, 70, 80, };
string[] name = new string[] { "Sally", "Joe", "Sue", "Pete", "Tom", };
double sum = 0;
double average;
int x = 4;
int y = 4;
int z = 0;
public highestGrade()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void addStudent_Click(object sender, EventArgs e)
{
if (x <= 9)
{
Array.Sort(grade, name);
name[x] = textBox1.Text;
grade[x] = Convert.ToInt32(textBox2.Text);
sum = sum + grade[x];
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
}
}
private void display_Click(object sender, EventArgs e)
{
outputText.Visible = true;
outputText.Text = textBox1.Text + " " + textBox2.Text;
}
private void lowestGrade_Click(object sender, EventArgs e)
{
Array.Sort(grade, name);
outputText.Visible = true;
outputText.Text = name[z] + " " + grade[z];
}
private void button4_Click(object sender, EventArgs e)
{
Array.Sort(grade, name);
outputText.Visible = true;
outputText.Text = name[y] + " " + grade[y];
}
private void averageGrade_Click(object sender, EventArgs e)
{
for (int y = 0; y < 5; y++)
{
sum = sum + grade[y];
}
average = sum / grade.Length;
string avgOutput = Convert.ToString(average);
outputText.Visible = true;
outputText.Text = "Class Average: " + avgOutput;
y++;
}
}
}
I need the program to take input for grade/name up to 10 students, while being able to output the lowest/highest grade continually whenever the user clicks. It also needs to output the total average continuously whenever the user clicks.
The average is not calculating correctly, it keeps adding to the sum for each time the average button is clicked and I cannot get the highest grade to hold its value. For example: if i enter a new grade as 100 then click highest grade, it displays that grade which is what I want. But for the next grade if i enter 95, it replaces the 100 with the 95.
Any help would be appreciated thank you.
You have to reset the current sum before adding the grades again to calculate the average correctly:
private void averageGrade_Click(object sender, EventArgs e) {
sum = 0; // reset sum
for (int y = 0; y < 5; y++) {
sum = sum + grade[y];
}
average = sum / grade.Length;
string avgOutput = Convert.ToString(average);
outputText.Visible = true;
outputText.Text = "Class Average: " + avgOutput;
}
You can also use LINQ to calculate sums and averages, no need to write for loops:
using System.Linq;
var sum = grade.Sum();
var average = grade.Average();
As for the problem with lowest/highest grade: calculate these every time the button is clicked. Eliminate the global variables y, z.
private void lowestGrade_Click(object sender, EventArgs e) {
// this probably only needs to be sorted if a value is added or removed (addStudent_Click)
Array.Sort(grade, name);
outputText.Visible = true;
// first element (with index 0) will be the lowest because arrays are sorted now
outputText.Text = name[0] + " " + grade[0];
}
You can also use LINQ .First() and .Last() to access the first or last element of a collection or without the need of sorting use LINQ .Min() and .Max() methods.
This button is populate which means click on this button will auto generate random numbers .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int rid = RandomNumber(-111, 999);
int rid1 = RandomNumber(-111, 999);
int rid2 = RandomNumber(-222, 888);
int rid3 = RandomNumber(-333, 777);
int rid4 = RandomNumber(-222, 777);
int rid5 = RandomNumber(-333, 444);
int rid6 = RandomNumber(-555, 888);
int rid7 = RandomNumber(444, 999);
int rid8 = RandomNumber(111, 222);
int rid9 = RandomNumber(222, 333);
txt1.Text = rid.ToString();
txt2.Text = rid1.ToString();
txt3.Text = rid3.ToString();
txt4.Text = rid4.ToString();
txt5.Text = rid5.ToString();
txt6.Text = rid6.ToString();
txt7.Text = rid7.ToString();
txt8.Text = rid8.ToString();
txt9.Text = rid9.ToString();
}
The second button is sort list.
How to take all the numbers and follow acceding to put back in the 9 different textbox ?
This is the coding for button sortlist:
protected void Button2_Click(object sender, EventArgs e)
{
int no1;
int no2;
int no3;
int no4;
int no5;
int no6;
int no7;
int no8;
int no9;
//int answer;
no1 = int.Parse(txt1.Text);
no2 = int.Parse(txt2.Text);
no3 = int.Parse(txt3.Text);
no4 = int.Parse(txt4.Text);
no5 = int.Parse(txt5.Text);
no6 = int.Parse(txt6.Text);
no7 = int.Parse(txt7.Text);
no8 = int.Parse(txt8.Text);
no9 = int.Parse(txt9.Text);
int[] a = new int[] {no1,no2,no3,no4,no5,no6,no7,no8,no9 };
Array.Sort(a);
foreach (var str in a)
{
MessageBox.Show(str.ToString());
}
}
I can display sort ACS in MessageBox but I can't put the number ACS into textbox
But still can't get the answer, where was wrong?
Thank you for help.
You could throw the generated numbers into a list, sort the list and assign the numbers accordingly. Thus, txt1.Text = sortedRandList[0]; and so on for the rest.
To get slightly cleaner code, you could consider also throwing all the text boxes within a list, and eventually end up doing textBoxesList[i] = sortedRandList[i];. That should clean up the code a little bit.
You can create List of ints and then sort it like this :
List<int> rids = null;
protected void Button1_Click(object sender, EventArgs e)
{
rids = new List<int>()
{
RandomNumber(-111, 999),
RandomNumber(-111, 999),
RandomNumber(-222, 888),
RandomNumber(-333, 777),
RandomNumber(-222, 777),
RandomNumber(-333, 444),
RandomNumber(-555, 888),
RandomNumber(444, 999),
RandomNumber(111, 222),
RandomNumber(222, 333)
};
DisplayValues(); // use it if you want to show your values in UI
}
protected void sortButton_Click(object sender, EventArgs e)
{
rids.Sort();
DisplayValues()
}
private void DisplayValues()
{
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is TextBox) if(Controls[i]).ID.Contains("txt"))
(Controls[i] as TextBox).Text = rids[Int32.Parse(Controls[i].ID.Replace("txt", "")) - 1].ToString();
}
}
I'm working on a small programme for booking seats on an airplane - And I keep getting this error. i want the programme to show me which seats on the plane (flysaeder) are being booking by what passenger (passagerer). Only, If I enter in more seats than I have passengers, it won't run - I need it to allow open seats (less "passagerer" than "flysaeder"). What am I doing wrong?
I'm kinda new at this, so I apologize for poor explanation.
Error occurs on "listeOverPassagerer[index] = listeOverPassagerer[i];".
namespace eksamenvingerne
{
public partial class Form1 : Form
{
int flysaeder;
int passagerer;
Random tilfældighed = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
{
int.TryParse(txtsaeder.Text, out flysaeder);
int.TryParse(txtantalpassagere.Text, out passagerer);
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
else
{
int[] listeOverPassagerer = Enumerable.Range(0, passagerer).ToArray();
int[] flypladser = new int[flysaeder];
for (int i = 0; i < flysaeder; i++)
{
int index = tilfældighed.Next(0, passagerer);
flypladser[i] = tilfældighed.Next(i, passagerer);
flypladser[i] = listeOverPassagerer[index];
listeOverPassagerer[index] = listeOverPassagerer[i];
}
for (int i = 0; i < flypladser.Length; i++)
{
listBox1.Items.Add("Sæde #" + i + ": Passagernr.:" + flypladser[i]); //listboxen udskriver indholdet af hver eneste plads.
}
}
}
}
}
}
Your logic actually is causing this problem:
First you make sure that passagerer <= flysaeder
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
Then you do a for loop from 0 to flysaeder -1
for (int i = 0; i < flysaeder; i++)
But flysaeder might be larger than passagerer hence your access of listeOverPassagerer[i] will throw an exception since listeOverPassagerer is of length passagerer