为什么以下代码不能运行private 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()); } } } private 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; } private static int getcount(Students[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] != null) ; count++; } return count; } private static boolean contains(Students[] arr, int id) { for (int i = 0; i < arr.length; i++) { //依次或取数组里面的每一个对象 Students stu = arr[i]; //获取学生的id int sid = stu.getId(); //进行比较 if (sid == id) { return true; } } //循环结束 return false; } }
时间: 2024-01-11 07:03:07 浏览: 66
这段代码缺少一个类的定义,其中的方法都是静态方法,可能是在某个类中定义的。如果没有这个类,那么这些方法就无法调用,也就无法运行。同时,getcount方法中的if语句有误,应该是判断是否为null,而不是分号。可以按照如下方式进行修改:
```
public class StudentManager {
private 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());
}
}
}
private 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;
}
private static int getcount(Students[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
count++;
}
}
return count;
}
private static boolean contains(Students[] arr, int id) {
for (int i = 0; i < arr.length; i++) {
Students stu = arr[i];
int sid = stu.getId();
if (sid == id) {
return true;
}
}
return false;
}
}
```
此时,可以在其他类中通过StudentManager.printArr等方法来调用这些静态方法。
阅读全文