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.
Related
I'm a complete beginner and trying to create a Times Table game app that asks the user to input a number, generates a multiplication sum, and then checks if it's the write answer to deliver a congratulations message and then adds the score.
I've managed to generate the random number, but when I input the correct answer I get the Incorrect message which makes me think that the random number is not pulling through to the second button. Any help much appreciated!
Button 1
private void button1_Click(object sender, EventArgs e)
{
userInput = Convert.ToInt32(textBox1.Text);
if (userInput >= 1 && userInput <= 10)
{
Random rNum = new Random(); //uses built in function Random()
int rrNum = rNum.Next(1, 12); // creates a number between 1 and 12
label5.Text = (Convert.ToString(rrNum) + " x " + userInput);
}
}
Button 2
private void button2_Click(object sender, EventArgs e)
{
userAnswer = Convert.ToInt32(textBox2.Text);
Random rNum = new Random();
int rrNum = rNum.Next(1, 12);
if (userAnswer == userInput * rrNum)
{
label8.Text = "Congratulations!";
pictureBox1.Enabled = true;
pictureBox1.Visible = true;
}
else
{
label8.Text = ("Incorrect, try again!");
}
}
My question is about.
if i type easter bunny it needs to get shown 10x using the while statement.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int paashaas = 0;
int p = paashaas;
while (p <= 4)
{
MessageBox.Show("The value of i is : " + paashaas);
paashaas = paashaas + 1;
}
}
This seems unreal to me
What you're doing in the below code is:
making an int (paashaas), setting it to 0,
then making another int (p), setting the value of the second int (p) also to 0,
then keep checking the second int (p) in the while loop, while changing the first int (paashaas) every time. Because of this, you will get stuck in the while loop. The value of p doesn't get changed, only the value of paashaas.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int paashaas = 0;
int p = paashaas;
while (p <= 4)
{
MessageBox.Show("The value of i is : " + paashaas);
paashaas = paashaas + 1;
}
}
Also, i would use a for loop if i were you, if you want to do a certain action x times. For example take this code:
for(int i=1; i<=4; i++)
{
MessageBox.Show("The value of i is: " + i);
}
This code will show 4 message boxes, with the text:
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
I think the working code that you're looking for is:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text == "easter bunny")
{
for(int i=0; i<10; i++)
{
MessageBox.Show($"You entered easter bunny in the textbox! {i}");
}
}
}
I have one textbox designated for "score" and another for "scores." Along with these two textboxes, I have a button called "add score." The score textbox handles 1 score. Every time I click the add score button, it should add a new score to the scores textbox. For example, if I enter "33" as the first score and click the add score button, then enter "45" and click the add score button, the scores textbox should display "33, 45." I want exactly 3 scores, and the 3 scores to display separately as a string in the scores textbox.
So far the only idea I had was to declare an array.
private void btnAddScore_Click(object sender, EventArgs e)
{
string name = txtName.Text;
int score = Convert.ToInt32(txtScore.Text);
int[] scores = new int[2];
}
You probably want to create your array before-hand so that it will be available for use when the button gets clicked. Instead of creating one inside to button handler.
With array you can use to show all the scores in the scores array as a string (comma separated):
string newString = string.empty;
foreach(int s in scores)
{
int n = 1, slen = scores.length;
if(n == 1 || n >= slen)
{ separator = ""; }
else
{ separator = ", ";}
newString = newString + separator + s.ToString();
n += 1;
}
Or static:
private void btnAddScore_Click(object sender, EventArgs e)
{
string name = txtName.Text;
if(Scores.length <= 3)
{
txtScores.Text = txtScores.Text.ToString() + ", " + txtScore.Text.ToString();
}
}
I will suggest you this approach:
private void btnAddScore_Click(object sender, EventArgs e)
{
string scores = txtName.Text;
if(!string.IsNullOrEmpty(scores) && scores.Split(',').Count() == 3)
{
MessageBox.Show("You can't enter more than three scores");
return;
}
if (string.IsNullOrEmpty(scores))
{
scores += txtScore.Text;
}
else
{
scores += ", " + txtScore.Text;
}
txtName.Text = scores;
}
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);
I am trying to retrieve one value from a combo box and place it into another combo box by using lists.
I successfully remove the value from the list, and implement it into the other list fine. But when I do this my list capacities malfunction and I get index out of bounds errors.
Scenario:
List Letter Selected: B
'Left Shift Button Pressed'
'B' Removed from Letters List
'B' Added to Numbers List
Print Out Values
Error: "Index was out of range. Must be non-negative and less than the size of collection
Line 66: Console.WriteLine("Numbers: " + numbers[i] + "\tIteration: " + i);
Number List Capacity: 8, Letters List Capacity: 4.
Number List: 1, 2, 3, 4, B. Letters List: A, C, D
CODE:
public partial class Form1 : Form
{
public List<string> letters = new List<string>();
public List<string> numbers = new List<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
InitialiseLists();
LoadListsIntoCombo();
}
public void InitialiseLists()
{
/*
* Add Letter Data
*/
letters.Add("A");
letters.Add("B");
letters.Add("C");
letters.Add("D");
/*
* Add Number Data
*/
numbers.Add("1");
numbers.Add("2");
numbers.Add("3");
numbers.Add("4");
}
public void LoadListsIntoCombo()
{
comboLetter.DataSource = letters;
comboNumber.DataSource = numbers;
}
public void PrintList()
{
/*
* Print Lists To Console
*/
for (int i = 0; i < numbers.Capacity; i++)
{
Console.WriteLine("NUM CAPACITY: " + numbers.Capacity);
Console.WriteLine("Numbers: " + numbers[i] + "\tIteration: " + i);
}
for (int i = 0; i < letters.Capacity; i++)
{
Console.WriteLine("LET CAPACITY: " + letters.Capacity);
Console.WriteLine("Letters : " + letters[i] + "\tIteration: " + i);
}
}
private void cmdLeft_Click(object sender, EventArgs e)
{
AddLetterToNumber(GetLetter());
RemoveLetter(GetLetter());
}
public void RemoveLetter(string value)
{
letters.Remove(value);
}
public void AddLetterToNumber(string value)
{
numbers.Add(value);
}
public string GetLetter()
{
string letter = comboLetter.SelectedItem.ToString();
return letter;
}
public int GetLetterIndex()
{
int letterIndex = comboLetter.SelectedIndex;
return letterIndex;
}
private void cmdRight_Click(object sender, EventArgs e)
{
PrintList();
}
}
}
Many thanks for any help you can provide.
Use Count property instead of Capacity. Because first one returns number of items contained in list. Second one is just says how many items you can add before list will be resized.
public void PrintList()
{
Console.WriteLine("Numbers count: " + numbers.Count);
for (int i = 0; i < numbers.Count; i++)
Console.WriteLine("Numbers: {0}\tIteration: {1}", numbers[i], i);
Console.WriteLine("Letters count: " + letters.Count);
for (int i = 0; i < letters.Count; i++)
Console.WriteLine("Letters : {0}\tIteration: {1}", letters[i], i);
}
You are using Capacity and not Count. Capacity is not the number of elements in the list.
Capacity: Gets or sets the total number of elements the internal data structure can hold without resizing.
Count: Gets the number of elements actually contained in the List<T>.
from here
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx