package Test;
public class StuTest {
public static void main(String[] args) {
Students[] stuArr = new Students[3];
Students s1 = new Students(1,"张三",18);
Students s2 = new Students(2,"李四",19);
// Students s3 = new Students(3,"王五",20);
stuArr[0]=s1;
stuArr[1]=s2;
// stuArr[2]=s3;
/*for (int i = 0; i < stuArr.length; i++) {
Students s = stuArr[i];
System.out.println(s.getId()+" "+s.getName()+" "+s.getAge());
}*/
Students s4=new Students(4,"zhaoliu",21);
boolean flag = contains(stuArr,s4.getId());
if (flag){
//y
System.out.println("the id is contain! ");
}else {
//no
int count = getCount(stuArr);
if(count == stuArr.length){
//over
Students[] newArr = creatNewArr(stuArr);
newArr[count]=s4;
printArr(newArr);
}else {
//no over
stuArr[count]=s4;
printArr(stuArr);
}
}
}
//遍历数组
public static void printArr(Students[] arr){
for (int i = 0; i < arr.length; i++) {
Students stu = arr[i];
if (stu!= null){
System.out.println(stu.getId()+" "+stu.getName()+" "+stu.getAge());
}
}
}
//计算数组是否存满
public static boolean contains(Students[] arr,int id){
for (int i = 0; i < arr.length; i++) {
Students stu = arr[i];
if(stu != null){
int sid = stu.getId();
if(sid ==id )
return true;
}
}
//循环结束后,return
return false;
}
//计算数组已经存了几个函数
public static int getCount(Students[] arr){
int count =0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]!=null){
count++;
}
}
return count;
}
//
public static Students[] creatNewArr(Students[] arr){
Students[] newArr = new Students[arr.length+1];
for (int i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
}
return newArr;
}
}