代码在CoffeeDregs中途停止运行

时间:2016-01-11 20:27:17

标签: java

我在CoffeeDregs中运行一些代码来查看代码是否有效,虽然DrJava编译代码很好,但它突然停止在Dregs的'Room room = rooms [i]'行中运行。谁能告诉我为什么会发生这种情况,以及如何解决这个问题呢?

如果我尝试运行DrJava中的代码,我会收到错误;显示java.lang.NullPointerException     在Hotel.checkIn(Hotel.java:24)

但是我不知道这是因为它是在Dregs中运行还是由于实际错误造成的。

我的代码如下;

class Hotel{
Room[] rooms;


Hotel() {

rooms = new Room[10];
Guest rob = new Guest("Rob");
Guest jing = new Guest("Jing");
Guest kevin = new Guest ("Kevin");

checkIn(rob);
checkIn(kevin);
checkIn(jing);

}

void checkIn(Guest guest){
 System.out.println(rooms.length);
 for (int i=1; i<rooms.length; i++){
   Room room = rooms[i];
     room.setGuest(guest);
     return;
   }
 }

public static void main(String[] args) {
  new Hotel();
 }
}


class Guest{
String guestName;

Guest(String n) {
this.guestName = n; 
}

}


class Room{
Guest guest = null;

public Guest getGuest(){
return guest;
}
  public void setGuest( Guest guest){
this.guest = guest;
}
}

1 个答案:

答案 0 :(得分:1)

我必须真正创造房间。通过

for (int i=0; i<rooms.length;i++){
rooms[i] = new Room();
}