Reputation: 313
Why here am I getting IndexOutofBoundsException 16 and Eclipse is pointing to the following code in the line:
if((temp[0][0] == '.' && temp[0][height - 1] == '.') ||
If I pass the following String:
String layout =
"..aa\n"+
"..aa\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"aaaa\n"+
"aaaa\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"...a\n"+
"";
into the method, then Im getting that error. Could smb please help me with this? Im pretty sure Im doing smth wrong in the conditionals after the loops.NOTE:Layout strings
for shapes must have at least one filled block in each of 0th row
, 0th column
, last row
, and last column
.
Thanks!
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
while(data.hasNextLine())
{
String line = data.nextLine();
width = line.length();
height++;
}
char[][] temp = new char[height][width];
Scanner data2 = new Scanner(layout);
for(int i = 0; i < height; i++)
{
String line = data2.nextLine();
for(int j = 0; j < width; j++)
{
if(line.charAt(j) != '.')
temp[i][j] = displayChar;
if(line.charAt(j) == '.')
temp[i][j] = line.charAt(j);
}
}
data2.close();
if((temp[0][0] == '.' && temp[0][height - 1] == '.') ||
(temp[height - 1][0] == '.' && temp[height - 1][width - 1] == '.'))
throw new FitItException("Empty borders!");
result = new CreateShape(height, width, displayChar, temp);
return result;
}
Upvotes: 1
Views: 79
Reputation: 3137
Look closely
temp[0][height - 1]
You are using height
in the second dimension
char[][] temp = new char[height][width];
But here, your height
is 1st dimension and width
is second.
Upvotes: 0
Reputation: 533442
You have temp[height - 1][width - 1]
where the first index is the height and the second lookup is the width. Now if you get these confused and use the height for the width, and the height is larger than the width, this is going to blow up.
Perhaps you intended temp[0][width -1]
Upvotes: 3