我試圖讓學生記錄應用程序,我可以的姓名和性別從文本文件中分離出來,但是當我試圖把它們放入數組,數組總是顯示爲空。當我單獨嘗試時,addStudent方法起作用。如何將我的姓名和性別變量放入數組中?
StudentList list = new StudentList();
string name = "";
string gender = "";
string line = "";
char[] selected = line.ToCharArray();
openFileDialog1.ShowDialog();
string file = openFileDialog1.FileName;
StreamReader sr = new StreamReader(file);
while ((line = sr.ReadLine()) != null)
{
studentList.Items.Add(line);
for (int i = 0; i < selected.Length; i++)
{
if (selected[i] != '(')
{
name += selected[i];
}
else if (selected[i] == '(')
{
gender += selected[i + 1];
break;
}
Student student = new Student();
student.setName(name);
student.setGender(gender);
list.addStudent(student);
}
}
這是其他類我爲了根據姓名和性別變量(不是想改變這種代碼)
class Student
{
private string name;
private string gender;
private DateTime birthDate;
public Student()
{
name = null;
gender = null;
birthDate = DateTime.Now; // default to set to current date
}
public void setName(string n)
{
name = n;
}
public string getName()
{
return name;
}
public void setGender(string g)
{
gender = g;
}
public string getGender()
{
return gender;
}
public void setBirthDate(DateTime bd)
{
birthDate = bd;
}
public DateTime getBirthDate()
{
return birthDate;
}
}
class StudentList
{
private Student[] list;
private int numStudents;
private int maxNum;
public StudentList()
{
maxNum = 300;
list = new Student[maxNum];
numStudents = 0;
}
public Student getStudent(int index)
{
Student ret = null;
try
{
ret = list[index];
}
catch (Exception ex)
{
MessageBox.Show("Exception has occurred: " + ex.Message);
}
return ret;
}
public bool addStudent(Student s)
{
bool ret = false;
if (numStudents < maxNum-1)
{
list[numStudents] = s;
numStudents++;
ret = true;
}
else
{
MessageBox.Show("Maximum Students exceeded");
}
return ret;
}
public int getNumStudents()
{
return numStudents;
}
public void clear()
{
for (int i = 0; i < numStudents; i++)
list[i] = null; // set to null
numStudents = 0;
}
public Student findStudent(string name)
{
Student ret = null;
for (int i = 0; i < numStudents; i++)
{
Student currentStudent = list[i];
if (currentStudent.getName() == name)
{
ret = currentStudent;
break;
}
}
return ret;
}
}
請提供一個輸入文件結構的示例。你可能可以用一個字符來分割一行,而不是循環通過一行字符。 – RokX
這應該是一個windowsform應用程序,並且StudentList list = new StudentList();是創建一個已經有另一個類的數組。 - LamaTo – user3054895
例如: 鮑勃(M) 瑪麗(F) 凱特瓊斯(F) -RokX – user3054895