Im trying to do a basic java task, there are ships and i have to give the coordinates of them using an import file in which there are characters representing the movements of the ships. (N = +1 to North, S= +1 to South, E= +1 to East, W= +1 to West)
I want to count the coordinates in a two dimensional Array, in which the first column represent the Vertical, the second column represents the Horizontal directions.
Get the following problem:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at robotok.main(robotok.java:36)
I marked line 36 in the source code.
ArrayList<String> control = new ArrayList<String>();
int coords[][] = new int[control.size()][2]; // index = robot sorszáma / [] Hosszúság / [] Szélesség
try {
Scanner scan = new Scanner(robotok);
while (scan.hasNextLine()) {
String line = scan.nextLine();
control.add(line);
}
} catch(Exception e){
}
for (int i = 0;i<control.size();i++) {
char[] directions = control.get(i).toCharArray();
for (int j =0;j<directions.length;j++) {
if (directions[j] == 'N') {
coords[i][0] --;
}else if (directions[j] == 'S'){
coords[i][0] ++;
}else if (directions[j] == 'W'){
coords[i][1] --;
}else if (directions[j] == 'E'){
coords[i][1] ++; /////THIS IS 36/////
}
}
}
for (int i =0;i<coords.length;i++) {
System.out.print("The "+i+". ship's coords: "+coords[i][0]+" ; "+coords[i][1]);
}
Instead of
use
The problem was that you intended to initialize
coords
based oncontrol
, which has a size of 0 before you add the elements. Later on, after the elements are added,control
becomes larger and you try to referencecoords
' element at certain indexes above its size. Hence the exception.