本文设计一个简单的班级管理系统,满足如下要求:
1、设计学生类Student,包含学号(String型)、姓名(String型)、性别(‘M’/'F’代表男/女)、年龄(int型)、是否党员(boolean型)、语文(double型)、数学(double型)等信息,要能够方便输出学生信息;
2、设计班级类BanJi,其中创建班级时可指定班级的最大容量。可向班级中批量增加学生信息,以及打印输出班级中所有学生的信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
import java.util.Scanner; class Student{ String id,name; char sex; int age; boolean isDy; double chinese,math; Student(String i,String n, char s, int a, boolean Dy, double c, double m){ id=i; name=n; sex=s; age=a; isDy=Dy; chinese=c; math=m; } public String toString(){ //此函数在用System.out.print(s)打印Student型对象s时,会被自动调用 String sex1 = "未知" ; //即此处控制如何输出学生信息 if (sex== 'M' || sex== 'm' ) sex1 = "男" ; else if (sex== 'F' || sex== 'f' ) sex1 = "女" ; String isDy1 = "未知" ; if (isDy == true ) isDy1 = "党员" ; else isDy1 = "非党员" ; return id+ " " +name+ " " +sex1+ " " +age+ " " +isDy1+ " " +chinese+ " " +math; } void print() { System.out.print( this ); } } class BanJi{ //班级类,实际上是存储学生的顺序表,数组+表长 Student [] s; // 此处并未创建数组对象,仅是数组的引用 int len; BanJi( int x){ s = new Student[x];} //此处创建【数组】对象,而非Student对象,用[]而不是()! void append() { // 向班级中批量增加学生元素 int i= 0 ; String id,name; char sex; int age; boolean isDy; double chinese,math; System.out.print( "按如下格式输入:\n" ); System.out.print( "000 张三 F 20 true 33.44 66\n" ); System.out.print( "请输入:\n" ); Scanner sc = new Scanner(System.in); while (sc.hasNext() == true ) { id = sc.next(); name = sc.next(); String xb = sc.next(); sex = xb.charAt( 0 ); // 不能直接读取char型,xb.charAt(0)取字符串xb的第一个字符 age = sc.nextInt(); isDy = sc.nextBoolean(); chinese = sc.nextDouble(); math = sc.nextDouble(); //必须创建一个Student型对象,并将其填入数组s s[i] = new Student(id,name,sex,age,isDy,chinese,math); i++; } //end-while 必须输入结束符才能使hasNext()为假 len = i; } void print() { for ( int i= 0 ;i<len;i++) System.out.print(s[i]+ "\n" ); } } class App{ public static void main(String [] args) { BanJi h = new BanJi( 50 ); h.append(); h.print(); } } |
//本例掌握:
1、系统性地学习了Scanner读取不同类型数据、读取未知数量的数据(haxNext()–面向String型、hasNextInt()、hasNextDouble())、如何结束输入(ctrl+Z);
2、重点: Student[] s=new Student[100]; 创建的是一个数组对象,而非Student对象
注:s是 一个Student[]型 数组对象,内有100个空指针(即null),
如果希望使用st[i].show(); ,s[i]必须先创建对象,然后才能使用。即:s[i]=new Student(…); //注此处使用圆括号,即调用了Student的构造函数
否则,将会产生空指针引用异常。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/m0_46527503/article/details/109405359