计蒜客-----泥塑课
一开始不知道错在了哪里,一直报空指针错误,后来才发现是对象数组没理解好
classroom room[] = new classroom[num];
只是声明了对象数组,并未初始化,所以直接使用room[i]会报空指针错误,正确的应该如下
classroom room[] = new classroom[num];
for (int i = 0; i < num; i++) {
room[i] = new classroom();
}
声明,并且初始化变量,接下来才可以使用.
完整代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
List<String> children = new ArrayList<String>();
int num;
while(true){
num = input.nextInt();
if(num!=-1){
//这里只是声明数组,还要创建对象
classroom room[] = new classroom[num];
for (int i = 0; i < num; i++) {
room[i] = new classroom();
}
for (int i = 0; i < num; i++) {
room[i].x = input.nextInt();
room[i].y = input.nextInt();
room[i].z = input.nextInt();
room[i].name = input.next();
}
children.add(judge(room));
}else{
break;
}
}
for (String string : children) {
System.out.println(string);
}
}
public static String judge(classroom room[]){
int avg = valuesum(room)/room.length;
int temp1 = 0,temp2 = 0;
for (int i = 0; i < room.length; i++) {
if(avg > room[i].volume()){
temp1 = i;
}else if(avg <room[i].volume()){
temp2 = i;
}
}
String temp = room[temp2].name+" took clay from "+room[temp1].name;
return temp;
}
public static int valuesum(classroom room[]) {
int sum = 0;
for (int i = 0; i < room.length; i++) {
sum = sum + room[i].volume();
}
return sum;
}
}
class classroom{
int x = 0;
int y = 0;
int z = 0;
String name = "";
public int volume() {
return x*y*z;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。