• Advertisement
Sign in to follow this  

Why does this code not work?

This topic is 1737 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

OperatingRoom[] room = new OperatingRoom[3];
		for(int i = 0; i < 3; i++)
		{
			room = new OperatingRoom;
			System.out.println("Op room #" + i);
			room = new OperatingRoom();
			room.fillRoom(opRoom);
			room.display();
		}

 

it gives me this error: 

 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at readPatient.main(readPatient.java:54)

 

I don't get why it gives this error when, as you can see, there's no ArrayIndexOutOfBounds

Share this post


Link to post
Share on other sites
Advertisement

I haven't touched java in a long time, but it looks like on your first iteration through the loop, you're assigning a zero size array to the room variable. Then you reference it at index 0  -> that's out of bounds. Why do you have the "room = new OperationRoom" line?

Share this post


Link to post
Share on other sites

I haven't touched java in a long time, but it looks like on your first iteration through the loop, you're assigning a zero size array to the room variable. Then you reference it at index 0  -> that's out of bounds. Why do you have the "room = new OperationRoom" line?

I thought java had that but i removed it and it sorta worked. (It compiled good but didn't add the data in. :-D)

Share this post


Link to post
Share on other sites

You want:

 

room = new OperatingRoom();

 

When you say new OperatingRoom, you're creating a new array of OperatingRooms (not a single OperatingRoom), and then you're assigning it to the variable room. This means that just before the loop, you set room to an array of size 3 of OperatingRooms. However, on the first run through the loop, you reset room to a new array of size zero (because i is zero). Then, a couple lines later, you say room, but room is an empty array of length zero! You can't get anything out of it.

 

So to recap:

  1. You want to populate the array with OperatingRoom objects instead of resetting the array (which is why you say room = instead of room =)
  2. You want to say new OperatingRoom() to create an individual object, not new OperatingRoom (which creates an array)
Edited by Cornstalks

Share this post


Link to post
Share on other sites
OperatingRoom[] rooms = new OperatingRoom[3];

for(int i = 0; i < rooms.length; i++)
{
   System.out.println("Op room #" + i);
   rooms = new OperatingRoom();
   rooms.fillRoom(opRoom); //What is opRoom ? I guess you have a variabe not included in your snippet.
   rooms.display();
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement