我正在尝试编写一个程序,以允许用户选择一些学生,然后要求他输入他们的毕业证书。这样我将创建public int numberOfStu=0
来存储学生人数,并创建public double [] grad
来保存名为grade
的班级的成绩。
我有两个问题:
1-我不能使grad
的长度与numberOfStu
的值相同
这是我的代码:
class grade
{
public int numberOfStu=0 ;
double[] grad = new double [numberOfStu]; // here is error
public grade()
{ }
public grade(int numStu, double [] Grads){
numberOfStu = numStu;
grad = Grads;
}
public int number() {
Console.Write("enter number of student:");
return numberOfStu = Int16.Parse(Console.ReadLine());
}
public double [] Gread(int numberOfStu) {
for (int i=0 ; i< numberOfStu; i++) {
grad[i] = double.Parse(Console.ReadLine());
}
return grad;
}
public void print()
{
Console.WriteLine("Number of students are {0}", numberOfStu);
for (int i = 0; i < numberOfStu; i++) {
Console.WriteLine("Gread of studen {0} is {1}", i + 1, Gread[i]);
}
}
}
2-我不知道如何在主类中调用Gread
函数,将其抛出数组函数。
这是主要代码:
static void Main(string[] args)
{
grade gread1 = new grade();
gread1.number();
gread1.Grad(gread1.number()); //here is error
gread1.print();
}
答案 0 :(得分:0)
您可以尝试一下重构:
public class Grades
{
private double[] _Items;
public int Count
{
get
{
return _Items.Length;
}
}
public Grades()
{
}
public Grades(double[] grades)
{
_Items = grades;
}
public int Resize()
{
Console.Write("Enter number of students:");
int.TryParse(Console.ReadLine(), out int count);
if ( _Items == null )
_Items = new double[count];
else
Array.Resize(ref _Items, count);
return Count;
}
public double[] Initialize(int count)
{
if ( _Items == null )
_Items = new double[count];
else
Array.Resize(ref _Items, count);
for ( int i = 0; i < _Items.Length; i++ )
{
Console.WriteLine("Enter grade of student {0}:", i + 1);
double.TryParse(Console.ReadLine(), out _Items[i]);
}
return _Items;
}
public void Print()
{
if ( _Items == null )
Console.WriteLine("There is no students.");
else
{
Console.WriteLine("Number of students are {0}", _Items.Length);
for ( int i = 0; i < _Items.Length; i++ )
Console.WriteLine("Grade of student {0} is {1}", i + 1, _Items[i]);
}
}
}
static void Test()
{
var g = new Grades();
g.Initialize(5);
g.Print();
}
结果:
Enter grade of student 1:
1
Enter grade of student 2:
2
Enter grade of student 3:
3
Enter grade of student 4:
4
Enter grade of student 5:
5
Number of students are 5
Grade of student 1 is 1
Grade of student 2 is 2
Grade of student 3 is 3
Grade of student 4 is 4
Grade of student 5 is 5
您可以将Grades
重命名为Students
,并将_Items
重命名为_Grades
。