0
int loc = 0 ;
int place = loc*3+1;
ArrayList<String> map = new ArrayList<String>( 
        Arrays.asList("|"," ","|\n",    "|"," ","|\n",    "|"," ","|\n",    
"|"," ","|\n", " ‾\n"));

Above is my Array list and some variables to keep track of the location of the spaces inside the array list. the Arraylist's purpose is to create a little map when its printed. The map looks like below. The blank spaces, where the character can be can be found every three index values at 1,4,7,and 10.

| |
| |
| |
| |
 ‾

The method I am having trouble with is below. Its purpose is to check if there is a blank space "above" the character. If there is a blank space it will return the word North and if there isn't it should return No.

 public static String moveN( ArrayList<String> map, int place){
  String movenorth = "";
  String positionvalue = map.get(place-3);

if (place-3 <= 0){
  movenorth = "No";
} else {
   if (positionvalue.equals(" "))
        movenorth = "North"; 
}
 return(movenorth);
}

Instead of returning No, it returns

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2

How might I get around this as my if statement is obviously not working as I wanted it to.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • 2
    Your if statement appears **after** you get the element at place - 3. – JB Nizet Dec 03 '18 at 18:45
  • 1
    You need to check that `place-3` is more than or equal to zero *before* you call `map.get(place -3);` – GBlodgett Dec 03 '18 at 18:46
  • 1
    Move `String positionvalue = map.get(place-3);` down inside the `else` block. – Dawood ibn Kareem Dec 03 '18 at 18:46
  • When you pass `1` as parameter `place` and call `map.get(place-3)` afterwards, you are trying to access the item at position `-2` of the `ArrayList`. That will never be possible due to indexes starting at 0, increasing... – deHaar Dec 03 '18 at 18:46
  • When accessing an array or list using a calculated index always make sure the result of the calculation is >= 0 and < then the size of the array/list – Joakim Danielson Dec 03 '18 at 18:50

2 Answers2

0

Your if is working, but the exception is being thrown because of this line:

String positionvalue = map.get(place-3);

Be sure to check you are not accessing an out of bound index before getting the position value.

dglozano
  • 6,369
  • 2
  • 19
  • 38
0

From the message, it looks like place = 1, and when you do place-3, it is trying to do map.get(-2) You should probably do a bounds check that looks something like this in the beginning if(place < 3){return "whatever you want when place is less than 3";}

Justin
  • 1,356
  • 2
  • 9
  • 16