c#建⽴⼀个学⽣类,包括私有字段:学号、姓名、班级、年龄
1. 建⽴⼀个学⽣类,包括私有字段:学号、姓名、班级、年龄,包括公共属性:学号、姓名、班级、年龄
writeline输出数值变量2. 实例化4个学⽣对象,并存储到学⽣类型数组中
3. ⽤户输⼊要查询的学号,搜索数组中是否有相应学⽣,如果有,在屏幕输出此学⽣所有信息;如果没有,屏幕输出查⽆此⽣的提⽰。
4. 在屏幕输出所有学⽣信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
class Student
{//创建⼀个学⽣类,有学号,姓名,班级,年龄
private int id;
private string name;
private string clas;
private int age;
public Student(int id,string name,string clas,int age)
/
/构造函数,⽤来初始化
{
this.id = id;
this.name = name;
this.clas = clas;
this.age = age;
}
//定义属性
/*属性是c#特有的,通常是变量的⾸字母⼤写
get⽤来返回类成员的值
set⽤来给类成员赋值,当然也可以对值进⾏判断,⽤value进⾏赋值*/
public int Id
{
get
{
return id;
}
set
{
id =value;
}
}
public string Name
{
get
{
return name;
}
set
{
name =value;
}
}
public string Clas
{
get
{
return clas;
}
set
{
clas =value;
}
}
public int Age
{
get
{
return age;
}
set
{
age =value;
}
}
}
static void Main(string[] args)
{
/*
定义四个对象,进⾏初始化,之后将其复制到数组中
然后输⼊要查新的id,利⽤循环和数组中对每⼀个成员⽐较 */
Student s1 =new Student(03061,"詹姆斯","计科1",36); Student s2 =new Student(03062,"库⾥","计科2",31); Student s3 =new Student(03063,"利拉德","计科3",32); Student s4 =new Student(03064,"欧⽂","计科4",28); s4.Age =2;
Student[] s =new Student[4];
s[0]= s1;
s[1]= s2;
s[2]= s3;
s[3]= s4;
int id_find;
int flag =0;
id_find =int.Parse(Console.ReadLine());
for(int i =0; i <4; i++)
{
if(id_find == s[i].Id)
{
Console.WriteLine("学⽣id:"+ s[i].Id);
Console.WriteLine("学⽣姓名:"+ s[i].Name);
Console.WriteLine("学⽣班级:"+ s[i].Clas);
Console.WriteLine("学⽣年龄:"+ s[i].Age);
flag =1;
}
}
if(flag ==0)
{
Console.WriteLine("查⽆此⽣!");
}
Console.WriteLine("--------------------------------");
Console.WriteLine("输出全部学⽣:");
for(int i =0; i <4; i++)
{
Console.WriteLine("学⽣id:"+ s[i].Id);
Console.WriteLine("学⽣姓名:"+ s[i].Name);
Console.WriteLine("学⽣班级:"+ s[i].Clas);
Console.WriteLine("学⽣年龄:"+ s[i].Age);
Console.WriteLine();
}
Console.ReadLine();
Console.ReadLine();
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论