(对象类作为参数的方法)



/**
 *  班类
 * @author Administrator
 */
public class Class {
Student [] stu=new Student[3];//创建一个 Student类型的 学生数组
/**
* 增加学生
* @param 一个学生
*/
//获得为班级添加学生,添加进数组中
public void addStu(Student student){//有参数  Student类型 的 输入值(student)
for(int i=0;i<stu.length;i++){//数组长度 录入 增加的 学生资料 参数
if (stu[i]==null) {
stu[i]=student;//将 学生资料存入 Student类型的 数组当中
break;
}
}
}
//对象类(学生类) 作为返回值  create创造
/**
* 关键代码
* @param n
* @param a
* @return Student
*/
//Student 类型的类
public Student createStu(String n,int a){
Student stu=new Student();//创建 学生类 对象
stu.name=n;//引用对象 属性(姓名) 并将 带参 方法中的值 赋给其 属性
stu.age=a;//引用对象 属性(年龄) 并将 带参 方法中的值 赋给其 属性
return stu;// 返回其 对象类(学生类)类型
}
//显示 数组中的内容
public void showStu(){
for(int i=0;i<3;i++){
if (stu[i]!=null) {
stu[i].show();//用   数组名stu 点操作符“.” 调用Student类中的方法
//显示 内容:
//(例)_System.out.println("学生姓名为:"+name);
//(例)_System.out.println("学生年龄为::"+age);
}

}
}

}



/**
* 学生类
* @param 
*/
public class Student {
//定义属性
String name;//学生姓名
int age;//学生年龄
/*String age;*/
//定义方法
public void show(){
System.out.println("学生姓名为:"+name);
System.out.println("学生年龄为::"+age);
}

}



import java.util.Scanner;




public class Test {


/**
* 14章节
* 循环输入(录入)调用对象作为参数的方法(示例代码)
* @param args
*/
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
Class class1=new Class();//创建一个对象(班的类)
for(int i=0;i<3;i++){//循环输入3次录入的信息
System.out.println("请输入学生姓名");
String n=input.next();
System.out.println("请输入学生年龄");
int a=input.nextInt();
/**
* 关键代码
*/
//声明了一个 Student类型  创建一个Student类型的 变量名接收 传参的内容
Student ssss=class1.createStu(n, a);
class1.addStu(ssss);//调用方法 将其实参数值传输 该方法中进入录入
}
class1.showStu();//调用方法显示存入Student类型 的数组内容


}


}


猜你喜欢

转载自blog.csdn.net/rinvay_cui/article/details/78777069