- 爱易网页
-
C#教程
- 新手怎么正确调用方法
日期:2014-05-18 浏览次数:20869 次
新手求助:如何正确调用方法
我设置了score[]来存放类score的数据,想用input output 和 toave完成输入、输出和求平均分,但是总出现空值引用异常,求教
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class score
{
public string name;
public int code;
public int csharp, english, mathm;
public float avers;
public void toave(ref score st)
{
st.avers = (st.csharp + st.english + st.mathm) / 3;
}
public score (int n1,score st1)
{
Console.WriteLine("下面输入第{0}个学生信息", n1 + 1);
Console.WriteLine("输入姓名、学号、C#成绩、英语、数学");
st1.name = Console.ReadLine();
st1.code = Convert.ToInt32(Console.ReadLine());
st1.csharp = Convert.ToInt32(Console.ReadLine());
st1.english = Convert.ToInt32(Console.ReadLine());
st1.mathm = Convert.ToInt32(Console.ReadLine());
}
public void output(ref score st2)
{
Console.WriteLine("{0,6} {1,4} {2,4} {3,4} {4,4} {5,4}", st2.name, st2.code, st2.csharp, st2.english, st2.mathm, st2.avers);
}
}
class Program
{
static void Main(string[] args)
{
int n;
Console.WriteLine("请输入人数");
n=Convert.ToInt32(Console.ReadLine());
score[] s=new score[n];
for (int i = 0; i < n; i++)
{
s[i].name = "1";
s[i].code = 1;
s[i].csharp = 1;
s[i].english = 1;
s[i].mathm = 1;
}
for (int i = 0; i < n; i++)
{
s[i].score(n,s[i]);
}
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
{
score temp;
if(s[i].avers>s[j].avers)
{
temp=s[j];
s[j]=s[i];
s[i]=temp;
}
}
for(int i=0;i<n;i++)
s[i].toave(ref s[i]);
for(int i=0;i<n;i++)
s[i].output(ref s[i]);
Console.ReadKey();
}
}
}
------解决方案--------------------
写得好乱阿~按你的意思改了一下~~你的面向对象思想有点问题啊~还有ref的用法最好去看看~~
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class score
{
private string name;
private int code;
private int csharp, english, mathm;
private float avers;
public float Avers
{
get { return avers; }
set { avers = value; }
}
public void toave()
{
this.avers = (this.csharp + this.english + this.mathm) / 3;
}
public score()
{
this.name = "";
this.code = 0;
this.csharp = 0;
this.english = 0;
this.mathm = 0;
this.avers = 0;