So I am trying to figure out how to print out a list of bowling names and scores in my program. It is way simple when using a console. I am trying to figure out how to print the array into a label on a GUI? Any suggestions? I tried if/else if statements but obviously it didn't work.
Here is my form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
const int MAX = 20;
const int TWO = 2;
int size = 0;
int count = 0;
//Array to store the names and scores so they can be printed
string[] nameAndScoreArray = new string[MAX];
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get info from the text box and store it in a variable
string aNameAndScore = nameTextBox.Text;
//Set the name and score
myBowlingTeam.SetNameAndScore(aNameAndScore);
//Get the information from the text box and store it in a variable
string nameAndScore = myBowlingTeam.GetNameAndScore();
if (nameAndScore != "")
{
string printName = "";
string printScore = "";
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Print the name of the bowler in the score box
string name = myBowlingTeam.GetAName();
//Change the int into a string then
//print the score of the bowler in the score box
int score = myBowlingTeam.GetAScore();
string strScore = String.Format("{0:d}", score);
//Store the name and score in an array to use them to print out the
//names and scores later
if (size < MAX)
{
nameAndScoreArray[size] = name;
nameAndScoreArray[size + 1] = strScore;
printName = nameAndScoreArray[size];
printScore = nameAndScoreArray[size + 1];
}
string strNameAndScore = printName + " " + printScore;
if (scoreLabel.Text == "")
{
scoreLabel.Text = strNameAndScore;
}
else if(scoreLabelTwo.Text == "")
{
scoreLabelTwo.Text = strNameAndScore;
}
else if(scoreLabelThree.Text == "")
{
scoreLabelThree.Text = strNameAndScore;
}
else if(scoreLabelFour.Text == "")
{
scoreLabelFour.Text = strNameAndScore;
}
else if(scoreLabelFive.Text == "")
{
scoreLabelFive.Text = strNameAndScore;
}
else if(scoreLabelSix.Text == "")
{
scoreLabelSix.Text = strNameAndScore;
}
else if(scoreLabelSeven.Text == "")
{
scoreLabelSeven.Text = strNameAndScore;
}
else if(scoreLabelEight.Text == "")
{
scoreLabelEight.Text = strNameAndScore;
}
else if(scoreLabelNine.Text == "")
{
scoreLabelNine.Text = strNameAndScore;
}
else if(scoreLabelTen.Text == "")
{
scoreLabelTen.Text = strNameAndScore;
}
//Clear the text box
nameTextBox.Clear();
}
else//If there is nothing in the text box
{
//Calculate the highest score and get the bowler's name
int highestScore = myBowlingTeam.CalcHighestScore();
string highestName = myBowlingTeam.GetHighestBowlerName();
//Calaculate the lowest score and get the bowler's name
int lowestScore = myBowlingTeam.CalcLowestScore();
string lowestName = myBowlingTeam.GetLowestBowlerName();
//Calculate the avg acore
double avgScore = myBowlingTeam.CalcAvgScore();
//Convert the numbers into strings
string strHighScore = String.Format("{0:d}", highestScore);
string strLowScore = String.Format("{0:d}", lowestScore);
string strAvgScore = String.Format("{0:f2}", avgScore);
//Display the information in the appropriate labels
highScoreNameLabel.Text = highestName;
highScoreLabel.Text = strHighScore;
lowScoreNameLabel.Text = lowestName;
lowScoreLabel.Text = strLowScore;
avgScoreLabel.Text = strAvgScore;
}
}
//Print Scores Method
//Purpose: To print the names and scores
//Parameters: An Array
//Returns: Nothing
public void PrintNamesAndScores(ref string[] anArray)
{
for(int i = 0; i < size; i++)
{
Console.WriteLine("{0} {1:d}", anArray[i], anArray[i + 1]);
i++;
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
}
// nothing
private void nameTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void scoreTextBox_KeyDown(object sender, KeyEventArgs e)
{
}
//Nothing
private void label10_Click(object sender, EventArgs e)
{
}
//nothing
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++ )
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
}
else
{
highestScore = scoreArray[i];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore()
{
int lowestScore = scoreArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
}
else
{
lowestScore = scoreArray[i];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalcAvgScore()
{
int sum = 0;
double avg = sizeOfScore;
//Add up all of the elements in the array
for (int i = 0; i < sizeOfScore; i++)
{
sum += scoreArray[i];
}
//Divide the sum by the size of the array
return avg = sum / avg;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
//Get Name and Score Method
//Purpose: To get the name and score
//Parameters: None
//Returns: A string
public string GetNameAndScore()
{
return nameAndScore;
}
//Set Name and Score Method
//Purpose: To set the name and score
//Parameters: A String
//Returns: None
public void SetNameAndScore(string aNameAndScore)
{
nameAndScore = aNameAndScore;
}
//Get Bowler Name Of Highest Score Method
//Purpose: To get the name of the bowler with the highest score
//Parameters: None
//Returns: A String
public string GetHighestBowlerName()
{
int highestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (highestScore > scoreArray[i])
{
highestScore = highestScore;
bowlersName = bowlersName;
}
else
{
highestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Get Bowler Name Of Lowest Score Method
//Purpose: To get the name of the bowler with the lowest score
//Parameters: None
//Returns: A String
public string GetLowestBowlerName()
{
int lowestScore = scoreArray[0];
string bowlersName = nameArray[0];
for (int i = 1; i < sizeOfScore; i++)
{
if (lowestScore < scoreArray[i])
{
lowestScore = lowestScore;
bowlersName = bowlersName;
}
else
{
lowestScore = scoreArray[i];
bowlersName = nameArray[i];
}
}
return bowlersName;
}
//Print Bowler's Names
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public string GetAName()
{
string name = "";
for (int i = 0; i < sizeOfName; i++)
{
name = nameArray[i];
}
return name;
}
//Print Bowler's Scores
//Purpose: To print the names the bowlers
//Parameters: None
//Returns: A String
public int GetAScore()
{
int score = 0;
for (int i = 0; i < sizeOfScore; i++)
{
score = scoreArray[i];
}
return score;
}
}
}
As a general solution, I'd suggest that using LINQ to output a list of one String per item and then using String.Join to join them into a single String is the most succinct option, e.g.
myLabel.Text = string.Join(Environment.NewLine, myArray.Select(obj => string.Format("{0}, {1}", obj.Property1, obj.Property2)));
Related
void Bubblesort(City []cities, int num)
{
for(int i = 0; i < num - 1; i++)
{
for (int j = 0; j < num - 1 - i; j++)
{
if (cities[j].CityTemperature < cities[j].CityTemperature + 1)
{
var tempvariable = cities[j];
cities[j] = cities[j + 1];
cities[j + 1] = tempvariable;
}
}
}
for (int i = 0; i < num; i++)
{
Console.WriteLine(cities[i].ToString());
}
}
static void Main(string[] args)
{
Console.WriteLine("welcome to enter the name of the city and its temperature between -60 and 60 Celsius \n you will have to enter 4 elements of each :-) \n\n\n\n");
City[] cities = new City[4];
Program myProgram = new Program();
var num = cities.Length;
for (int i = 0; i < cities.Length; i++)
{
cities[i] = new City();
Console.Write("Name of City ?: ");
cities[i].CityName = Console.ReadLine();
Console.Write("what Temp ?: ");
cities[i].CityTemperature = System.Convert.ToInt32(System.Console.ReadLine());
Console.Clear();
}
myProgram.Bubblesort(cities, num);
Console.WriteLine("press a button of choice and hit enter to close the program, \n Byebye :-)");
Console.ReadKey();
}
}
/// My City class
private string name;
private int temperature;
public string CityName
{
get { return name; }
set { name = value; }
}
public int CityTemperature
{
get { return temperature; }
set { temperature = value; }
}
public override string ToString()
{
return "City: " + CityName + " City temperature: " + CityTemperature;
}
So basically user input City name and City
temperature that are stored into fields of the class,
i want to bubblesort the array by the temperature so it will
make an output sorted from coldest to warmest.
can you see where to begin with ? i been trying to
figure out if im passing wrong arguments when calling the function
and been trying to change withing the loops and experimenting.
im thinking maybe that i dont compare the temperature values
and it does something else. however the sorting is never occuring.
appreciate the time you take to look at this.*
i've made an array with numbers.
i want to ad up the numbers form the array and show the result in a textbox.
i've to use the foreach loop.
i've already searched on the internet but i can't find anything that helped me.
this is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnsortar_Click(object sender, EventArgs e)
{
//opdr 9
int[] getallen = { 4,5,9,8,31,44,76,63,88,59 };
int index = 1;
int lengteArray = getallen.Length;
tbsortar.Text = getallen[0].ToString();
while (index < lengteArray)
{
Array.Sort(getallen);
tbsortar.Text = tbsortar.Text + "," + getallen[index].ToString();
index++;
}
//opdr 10
string[] namen = { "kees", "jan", "piet", "henk" };
Array.Sort(namen);
int lengteArray1 = namen.Length;
tbopdr10.Text = namen[0];
for (int i=1; i<lengteArray1; i++)
{
string newLine = Environment.NewLine;
tbopdr10.Text = tbopdr10.Text +newLine + namen[i] ;
}
//opdr 11
double totaal = 0;
foreach(int getal in getallen)
{
//toaal van getallen is 392
totaal += getal;
tbopdr11.Text = tbopdr11.Text + totaal;
}
}
}
Try this:
int[] Numbers = { 1, 2, 3 };
int Result = 0;
for (int i = 0; i < Numbers.Length; i++)
{
Result += Numbers[i];
}
TextBox1.Text = System.Convert.ToString(Result);
The textbox's name is TextBox1.
can't you just use sum?
getallen.Sum()
https://dotnetfiddle.net/sTn1kp
I keep getting this message "System.IndexOutOfRangeException: Index was outside the bounds of the array." when attempting to run a program I built, that utilized an exception catcher.
class StudentS
{
private List theStudentList;
public bool PopulateStudents(string path)
{
theStudentList = new List<Student>();
bool flag = false;
try
{
List<string[]> strArrayList = new List<string[]>();
using (StreamReader streamReader = new StreamReader(path))
{
string str;
while ((str = streamReader.ReadLine()) != null)
{
string[] strArray = str.Split(',');
strArrayList.Add(strArray);
}
}
for (int index1 = 0; index1 < strArrayList.Count; ++index1)
{
string[] strArray = strArrayList[index1];
Student student = new Student(strArray[0], strArray[1], strArray[2]); **where the error is**
int index2 = 3;
while (index2 < strArray.Length)
{
student.EnterGrade(int.Parse(strArray[index2]), int.Parse(strArray[index2 + 1]));
index2 += 2;
}
student.CalGrade();
theStudentList.Add(student);
}
}
catch (Exception e)
{
flag = true;
Console.WriteLine(e);
}
return flag;
}
public int ListLength
{
get
{
return theStudentList.Count;
}
}
public float StudentAverage(int index)
{
return theStudentList.ElementAt(index).Average;
}
public string StudentGrade(int index)
{
return theStudentList.ElementAt(index).LetterGrade;
}
public string StudentID(int index)
{
return theStudentList.ElementAt(index).ID;
}
public string StudentLastName(int index)
{
return theStudentList.ElementAt(index).NameLast;
}
}
class Student
{
private float average;
private ArrayList Earned;
private string letterGrade;
private string nameFirst;
private string nameLast;
private ArrayList Possible;
private string studentID;
public Student(string id)
{
studentID = null;
nameFirst = null;
nameLast = null;
Earned = new ArrayList();
Possible = new ArrayList();
}
public Student(string id, string first)
{
studentID = id;
nameFirst = null;
nameLast = null;
Earned = new ArrayList();
Possible = new ArrayList();
}
public Student(string id, string first, string last)
{
nameFirst = first;
nameLast = last;
studentID = id;
Earned = new ArrayList();
Possible = new ArrayList();
}
public float Average
{
get
{
return average;
}
}
public string ID
{
get
{
return studentID;
}
}
public string LetterGrade
{
get
{
return letterGrade;
}
}
public string NameFirst
{
get
{
return nameFirst;
}
set
{
nameFirst = value;
}
}
public string NameLast
{
get
{
return nameLast;
}
set
{
nameLast = value;
}
}
public void CalGrade()
{
int num1 = 0;
int num2 = 0;
foreach (int num3 in Earned)
num1 += num3;
foreach (int num3 in Possible)
num2 += num3;
average = num1 / (float)num2;
average = (float)Math.Round(average, 2);
if (average >= 0.9)
letterGrade = "A";
if (average >= 0.8 && average < 0.9)
letterGrade = "B";
if (average >= 0.7 && average < 0.8)
letterGrade = "C";
if (average >= 0.6 && average < 0.7)
letterGrade = "D";
if (average >= 0.6)
return;
letterGrade = "U";
}
public void EnterGrade(int earnedValue, int possValue)
{
Earned.Add(earnedValue);
Possible.Add(possValue);
}
}
I am unsure as to what I have done wrong. Thanks for any help!
Edit: I went ahead and added a majority of the code here, in hopes that this answers your questions better. The data set I am dealing with is 4 rows, that are grabbed into the student array.
index2 + 1 may be out of range in the expression strArray[index2 + 1] below:
while (index2 < strArray.Length)
{
student.EnterGrade(int.Parse(strArray[index2]), int.Parse(strArray[index2 + 1]));
index2 += 2;
}
To process two elements at a time, use index2 < strArray.Length - 1
You may have a problem if the file from your path has an empty row as last row.
You access strArray[0], strArray[1], strArray[2] no matter if it is an empty array or not.
Maybe you are missing an Array.resize(). // This worked for me
Array.Resize<string[]>(ref strArrayList , count+ 1); // Count is the current length of strArrayList
Flagged the two spots where you could run into trouble:
public bool PopulateStudents(string path)
{
theStudentList = new List<Student>();
bool flag = false;
try
{
List<string[]> strArrayList = new List<string[]>();
using (StreamReader streamReader = new StreamReader(path))
{
string str;
while ((str = streamReader.ReadLine()) != null)
{
string[] strArray = str.Split(',');
strArrayList.Add(strArray);
}
}
for (int index1 = 0; index1 < strArrayList.Count; ++index1)
{
string[] strArray = strArrayList[index1];
// below that, what makes you believe strArray's length is >= 3 ?
Student student = new Student(strArray[0], strArray[1], strArray[2]);
int index2 = 3;
while (index2 < strArray.Length)
{
// here index2 will be < strArray.Length, but index2+1 might be ==
student.EnterGrade(int.Parse(strArray[index2]), int.Parse(strArray[index2 + 1]));
index2 += 2;
}
student.CalGrade();
theStudentList.Add(student);
}
}
catch (Exception e)
{
flag = true;
Console.WriteLine(e);
}
return flag;
}
Note that your while loop could be replaced with:
for(int index2 = 3; index2 < strArray.Length - 1; index2 += 2)
{
student.EnterGrade(...);
}
This is difficult to diagnose because you provided limited information. If I could see the file you are running through your program, fed in as path, I would be able to compare what the function is attempting to do to the data it is trying to do it on. That said, this looks familiar to me so I will give solving it a try and at least give you a tool to try on it.
I experienced a similar issue with a program that needed to read a CSV file for a graphics program. The problem was that when the CSV file was created, an empty line was left at the end. This left me with an empty array to represent the last line in the file.
Also, have you verified that the arrays that are added to strArrayList are consistently sized?
If you check for this empty line at the end of your file and it does not exist and if you check for commas left at the end of the lines in your file passed in as path then you can try the edits I made above to get an idea of which line(s) in your CSV file is causing the problem. I commented all the edits I made with “EDIT:” so they would be easy to find. Without more information, I cannot fix the problem, but I can maybe help you look in the right direction.
The edited code with the output for line numbers in your file which are associated with errors is below. Good luck!
public bool PopulateStudents(string path)
{
theStudentList = new List<Student>();
bool flag = false;
// EDIT: NEW VARIABLE int lineCounter declared and initialized before try block so it remains in scope when the catch block is called
int counter = 0;
try
{
List<string[]> strArrayList = new List<string[]>();
using (StreamReader streamReader = new StreamReader(path))
{
string str;
while ((str = streamReader.ReadLine()) != null)
{
string[] strArray = str.Split(',');
strArrayList.Add(strArray);
}
}
for (int index1 = 0; index1 < strArrayList.Count; ++index1)
{
// EDIT: UPDATE lineCounter
++lineCounter;
string[] strArray = strArrayList[index1];
Student student = new Student(strArray[0], strArray[1], strArray[2]);
int index2 = 3;
while (index2 < strArray.Length)
{
student.EnterGrade(int.Parse(strArray[index2]), int.Parse(strArray[index2 + 1]));
index2 += 2;
}
student.CalGrade();
theStudentList.Add(student);
}
}
catch (Exception e)
{
flag = true;
Console.WriteLine(e);
// EDIT: PRINT CURRENT LINE
Console.WriteLine(“error at line in file = “ + lineCounter);
}
return flag;
}
I want to add the elements from the textboxes to the array but every time I try adding the names it throws an exception. I want to add the elements after the button is clicked.
private void Grade_Click(object sender, EventArgs e)
{
string name;
double grade;
nametextbox.Text = "";
gradetextbox.Text = "";
for (int i = 0; i < 10; i++)
{
grade = Convert.ToDouble(gradetextbox.Text);
grades[i] += grade;
name = nametextbox.Text;
names[i] += name;
}
}
You do this:
gradetextbox.Text = "";
Which sets the Text property to an empty string. Then you do this:
grade = Convert.ToDouble(gradetextbox.Text);
which is trying to convert the empty string to a double, which clearly does not work so it throws an exception.
What you probably need is this:
private double[] grades = new double[10]; // 10 grades
private string[] names = new string[10]; // 10 names
private int currentIndex = 0;
private void Grade_Click(object sender, EventArgs e)
{
if (currentIndex > 10)
{
MessageBox.Show("No more enteries allowed");
}
string name;
double grade;
if (double.TryParse(gradetextbox.Text, out grade))
{
grades[currentIndex] += grade;
}
else
{
MessageBox.Show("Grade enterd is not a valid grade");
return;// do nothing else
}
name = nametextbox.Text;
names[i] += name;
// now clear the textboxes so user can enter another value
nametextbox.Text = "";
gradetextbox.Text = "";
currentIndex = currentIndex + 1;
}
I'm trying to display 5 scores in an array, but unfortunately all I get in the message box for the results is 0.
Any help would be appreciated.
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
when the add button is clicked the scores are stored in the array up to 5 times.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}
You keep overwriting message in this loop:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
So it's only ever going to show the last value. You probably want to append to it instead:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}