C#定义一个class,如何对数组降序输出
实验内容:要求输入自定义的数目学生的姓名,性别,身高,体重,然后按身高降序输出。
using System;
namespace 简单的class使用
{
class Student
{
public int sxuhao;
public string sname;
public string ssex;
public double shight;
public double sweight;
public void AddData(string name,string sex,double hight,double weight)//添加数据方法
{
sname = name;
ssex = sex;
shight = hight;
sweight = weight;
}
}
class Program
{
//struct Student
//{
// public int xuhao;
// public string name;
// public string sex;
// public double hight;
// public double weight;
//}
static void Main(string[] args)
{
int i, j;
string name=null, sex=null;
double hight=0, weight=0;
Student x = new Student();//类名后面的“()”提供初始化列表,这实际上就是提供给构造函数的参数,系统根据这个初始化列表的参数个数、类型和顺序调用不同的重载版本,
Console.Write("请输入班级人数:");
int num = int.Parse(Console.ReadLine());//从控制台接受学生人数并且转换成int类型
Student[] stu = new Student[num];//根据学生总人数动态创建对象
for (i = 0; i < num; i++)//对Student类的对象数组进行初始化
stu[i] = new Student();
for (i = 0; i < num; i++)
{
//Console.WriteLine("请输入第{0}个学生姓名: ",i+1);
//name = Console.ReadLine();
//Console.WriteLine("请输入第{0}个学生性别: ",i+1);
//sex = Console.ReadLine();
x.sxuhao = i + 1;
for (; ; )//输入姓名,并且判断错误
{
Console.Write("请输入第{0}个学生的姓名:", i + 1);
name = Console.ReadLine();
if (name != "")
{
x.sname = name;
break;
}
else
{
Console.WriteLine("输入姓名不能为空,请重新输入!");
continue;
}
}
for (; ; )//输入性别,并且判断错误
{
Console.Write("请输入第{0}个学生的性别:", i + 1);
sex = Console.ReadLine();
if (sex != "")
{
x.ssex = sex;
break;
}
else
{
Console.WriteLine("输入性别不能为空,请重新输入!");
continue;
}
}
for (; ; )//输入身高,并且异常处理
{
Console.Write("请输入第{0}个学生的身高:", i + 1);
try
{
hight = double.Parse(Console.ReadLine());
if (hight >= 0)
{
x.shight = hight;
break;
}
}
catch
{
Console.WriteLine("身高输入有误!");
continue;
}
}
for (; ; )
{
Console.Write("请输入第{0}个学生的体重:", i + 1);
try
{
weight = Convert.ToDouble(Console.ReadLine());
if (weight > 0)
{
x.sweight = weight;
break;
}
}
catch
{
Console.WriteLine("体重输入有误!");
}
}
stu[i].AddData(name, sex, hight, weight);//将当前输入的学生信息存入对象数组内
}
for (i = 0; i < stu.Length - 1; i++)//根据身高排序
{
for (j = i + 1; j < stu.Length; j++)
{
Student s1 = (Student)stu[i];
Student s2 = (Student)stu[j];
if (s1.shight < s2.shight)
{
Student zjz = (Student)stu[i];
stu[i] = stu[j];
stu[j] = zjz;
}
}
}
Console.WriteLine("==============学生信息展示=================");
Console.WriteLine("姓名" + "\t" + "性别" + "\t" + "身高" + "\t" + "体重" + "\t");
for (i = 0; i < stu.Length; i++)//输出表格
{
Console.WriteLine(stu[i].sname + "\t" + stu[i].ssex + "\t" + stu[i].shight + "\t" + stu[i].sweight);
// Console.WriteLine(((Student)[i]).sxuhao + "\t" + ((Student)al[i]).sname + "\t" + ((Student)stu[i]).ssex + "\t" + ((Student)al[i]).shight + "\t" + ((Student)al[i]).sweight);
}
Console.ReadLine();
}
}
}
实验结果
