#c# #user-interface
#c# #пользовательский интерфейс
Вопрос:
Итак, я использую графический интерфейс с классом. Я делал это раньше, и я знаю, что большую часть времени вы создаете событие для кнопки. Затем, когда эта кнопка нажата, вы можете создать новый объект. В этом проекте, над которым я работаю, у меня есть текстовое поле, в которое я ввожу имя и оценку. Затем, когда я нажимаю имеющуюся у меня кнопку ввода, я хочу создать новый объект с помощью параметризованного конструктора и поместить имя и оценку в разные массивы, чтобы я мог ими манипулировать. Затем я хочу получить самые высокие, самые низкие и средние оценки. У меня были предыдущие проекты, в которых я просто создавал новый объект при нажатии кнопки. Но при этом я загружаю несколько объектов в одно текстовое поле. Итак, каждый раз, когда нажималась кнопка, я создавал новый объект. Что я хочу сделать, это создать объект один раз с помощью параметризованного конструктора, а затем добавить имена и оценки к массивам внутри класса. Есть предложения.
Метод bottom в моем классе form Я пытался обойти и сделать это таким образом, но это ничего не дало.
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
ПОЖАЛУЙСТА, ПОМОГИТЕ. Это похоже на мою единственную ошибку. Если я заставлю эту часть работать правильно, программа будет работать. Потому что я знаю, как работать с классом, чтобы получить желаемые результаты. Заранее спасибо.
Вот мой код класса:
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 = 0;
int size = 0;
for (int i = 0; i < MAX; i )
{
if (scoreArray[i] < scoreArray[i 1])
{
highestScore = scoreArray[i];
}
else
{
highestScore = scoreArray[i 1];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore(int[] anArrayOfInts, int sizeOfArray)
{
int lowestScore = 0;
while (sizeOfArray < MAX)
{
if (anArrayOfInts[sizeOfArray] < anArrayOfInts[sizeOfArray 1])
{
lowestScore = anArrayOfInts[sizeOfArray];
}
else
{
lowestScore = anArrayOfInts[sizeOfArray 1];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalculateAvgScore(int[] anArrayOfInts, int sizeOfArray)
{
int sum = 0;
double avg = 0;
//Add up all of the elements in the array
while(sizeOfArray < MAX)
{
sum = anArrayOfInts[sizeOfArray];
}
//Divide the sum by the size of the array
return avg /= sum;
}
//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 ;
}
}
}
Вот мой код Form1 для GUI:
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;
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();
}
//AboutToolStripMenuItem1_Click
//Purpose: To display student information
//Parameters: The sending object and the event arguments
//Returns: nothing
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Charlie BarbernCS 1400-X01nProject 9");
}
//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 the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
if (userInput != "")
{
//Create a new object with the parameterized constructor
// myBowlingTeam = new BowlingTeam(userInput);
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Clear the text box
nameTextBox.Clear();
}
else
{
int highestScore = myBowlingTeam.CalcHighestScore();
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
}
Комментарии:
1. Мне не ясно, в чем проблема. Если вам просто нужно одноразовое создание экземпляра Bowling Team, сделайте это в событии OnLoad формы.
Ответ №1:
Что мешает вам использовать класс для игроков внутри команды? Синхронизировать массивы в вашем решении кажется больше проблем, чем оно того стоит.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Observable
{
class BowlingTeam
{
public string TeamName { get; set; }
private readonly IList<Player> players = new ObservableCollection<Player>();
public IList<Player> Players
{
get
{
return players;
}
}
public void AddPlayer(string name, int score)
{
AddPlayer(new Player(name, score));
}
public void AddPlayer(Player p)
{
players.Add(p);
}
public Player HighestRanked()
{
if (Players.Count == 0)
{
// no players
return null;
}
int max = 0, index = -1;
for (int i = 0; i < Players.Count; i )
{
if (Players[i].Score > max)
{
index = i;
max = Players[i].Score;
}
}
if (index < 0)
{
// no players found with a score greater than 0
return null;
}
return Players[index];
}
public BowlingTeam()
{
}
public BowlingTeam(string teamName)
{
this.TeamName = teamName;
}
}
class Player
{
public string Name { get; set; }
public int Score { get; set; }
public Player()
{
}
public Player(string name, int score)
{
this.Name = name;
this.Score = score;
}
public override string ToString()
{
return string.Format("{0} {1:n2}", Name, Score);
}
}
}
которыми можно манипулировать как таковыми
BowlingTeam b1 = new BowlingTeam("SO");
b1.AddPlayer("Player 1", 100);
b1.AddPlayer("Player 2", 135);
b1.AddPlayer("Player 3", 90);
b1.AddPlayer("Player 4", 127);
Console.WriteLine("Highest ranked player: {0}", b1.HighestRanked());
Преимуществом для последующего использования является то, что вы можете зависать на OnCollectionChangedEvents ваших игроков, чтобы получать уведомления о добавлении / удалении игроков.