I am writing a program that contains apartment rooms. The program is supposed to determine the level of noise and pollution in a given room that is due to a combination of the room tenant's own behavior and the neighbors several rooms to the left and right. My problem is that the array index is out of bounds when the program searches for the room number. I need help on having the array index match up with the array with the room information. Here is my code:
import java.util.Scanner; public class Program04 { static Scanner console = new Scanner(System.in);
You should make sure that roomnumber +- i (where i is all possible radii) is allways inside the array range. Remember that room[0] does only have a neighbor on one side.
I think you geting error on this part of code: for(int count=0; count<=Radius; count++){ Room[y-count].getPollutionLevel(); Room[y+count].getPollutionLevel();
because earlear y was equal to roomNumber, lets say 22 and you created only 10 rooms array.
if you want to use such statment you must create room = new ApartmentRoom(i,"Jane", 450, 10, 10) - sa that index of array and room number match.
or you could write short method like: ApartmentRoom getRoom(int nr){ for(int j = 0; j < Room.length; j++){ if(nr == Room[j].getRoomNum()) return Room[j]; } }
when you can call it: for(int count=0; count<=Radius; count++){ ApartmentRoom a, b; a = getRoom(y-count); b = getRoom(y+count); a.getPollutionLevel(); b.getPollutionLevel();