How to fix ArrayIndexOutOfBoundsException in Java? [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I get an ArrayIndexOutOfBoundsException, but only when the getSubImage() function is there.
This is to loop through and get sprites.I've tried it without getsubimage and i've tried using different for loops though nothing has helped.
This is not the same as the thread I am being compared to, as I am using a for loop inside of another. The program works just fine without getSubimage, and the for loops work just fine. I do not know where the problem lies or what it is.
try {
BufferedImage spritesheet = ImageIO.read(
getClass().getResourceAsStream(
"/Sprites/SpriteSheet.gif"
)
);
sprites = new ArrayList<BufferedImage[]>();
for(int i = 0; i < 6; i++) {
BufferedImage[] bi =
new BufferedImage[i];
for(int j = 0; j < numFrames[i]; j++) {
bi[j] = spritesheet.getSubimage(
i * width,
j* height,
width,
height
);
}
sprites.add(bi);
}
}
catch(Exception e) {
e.printStackTrace();
}
I expect it to loop through this and get all the sprites. What actually happens is it doesnt get the subimage and it just throws an out of bounds exception.

Your program is trying to retrieve an element with index not available from an array. Check the line 15 (is numFrames already created some where?). It possible that you are not using a right array or numFrames does not have an element with that specific index. Try running a debugger and see which array is out of index.

Related

How to traverse through the diagonals? [duplicate]

This question already has answers here:
Loop diagonally through two dimensional array
(12 answers)
Closed 1 year ago.
It's giving outOfBounds every time. I have tried every possible alteration now but it's not giving the output. The O/P should be 7-4-8-1-5-9-2-6-3
for(int g=n-1; g>=0; g--) {
for(int i=g, j=0; i>=g; i++, j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
for(int g=0; g<n; g++) {
for(int i=0, j=i+g; j<n; i++,j++) {
System.out.print(a[i][j]) ;
}
System.out.println();
I think the first thing you can do is change the i>=g to a better limit.
As you are incrementing i positively, and i is already equal to g, it will keep going up past the limit of the array's bounds. Maybe i<(the limit of your bounds) should solve it.
If I was trying to iterate through a square matrix, I would use only one variable and iterate with a[i][i] to reduce confusion:
for (i=0; i > (your bounds); i++) {
System.out.println(a[i][i]);
}
This is the base logic but you seem to be trying to achieve something a little more advanced, so modify it as you see fit.

Index Out Of Bounds Exception: Invalid index 0, size is 0 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
So I have an android application and frequent forced close. Why on my logcat the following Method often causes errors?
static void solveTSP(int[][] valuesMatrix) {
shortestDistance = Integer.MAX_VALUE;
longestDistance = Integer.MIN_VALUE;
shortestPath = null;
int totalPlaces = valuesMatrix.length;
ArrayList<Integer> places = new ArrayList<>();
for(int i=0; i<totalPlaces; i++){
places.add(i);
}
int startPlace = places.get(0);// in logcat, this line is the cause of the Index error Out of Bounds Exception: Invalid index 0, size is 0. How does that happen?
int currentDistance = 0;
bruteForceSearch(valuesMatrix, places, startPlace, currentDistance);
}
If valuesMatrix is empty, then places will have a length of 0 and no values inside, hence the error when you try to do places.get(0).
1) Please try to log your valuematrix length, because it is clearly mentioned in error that valuesMatrix size is zero, so your palces list is also empty. And hence, when you try to get 0th element, it throws same exception.
2) Other thing is, you are just storing 0 to valuematrix length in places list, so, startplace will have value always zero(0).
The length of valuesMatrix is definately 0 which is getting assigned to totalPlaces.
So your 'for' loop does not run and nothing gets added to your ArrayList 'places'.
So when you are trying to get value from its zeroth position you are getting an exception.
Check the size of places variable, if it is grater than zero then only proceed with further statements as below:
for(int i=0; i<totalPlaces; i++){
places.add(i);
}
if (places.size() > 0) {
int startPlace = places.get(0);
}

ConcurrentModificationException with 2 Iterators and one ArrayList [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
I have a quick question that involves one ArrayList, 2 Iterators, and some nested for loops. Im trying to make a bit of a gravity engine using multiple gravity wells pulling on each other and moving around. To do this, Iv made an ArrayList of these gravity wells, all randomly places on the screen with a random size. Here it is for reference.
for(int i = 0; i < amount; i++){ // makes all
int mass = rand.nextInt(45,65);
int locX = rand.nextInt(50, getWidth()-100);
int locY = rand.nextInt(50, getHeight()-100);
Color cColor = rand.nextColor();
if(mass%8==0){
mass = rand.nextInt(25,35);
}
else if(mass%7==0){
mass = rand.nextInt(75,85);
}
Body body = new Body((double)locX,(double)locY,mass);
body.setFilled(true);
body.setColor(Color.WHITE);
body.setFillColor(cColor);
add(body);
bodys.add(body);
}
bodys is the name of the ArrayList containing everything. So my real problem comes to the Iterators. Heres the code thats giving me trouble:
public void move(){
Iterator<Body> eIter = bodys.iterator();
while(eIter.hasNext()){ // finding the thing we edit
Body edit = eIter.next();
int addX = 0, addY = 0;
int totalX = 0, totalY = 0;
double ex = edit.getX(), ey = edit.getY();
double eMass = edit.getMass(), eSize = edit.getHeight();
double eMoveX = edit.getMoveX(), eMoveY = edit.getMoveY();
int placeInArrayEdit = bodys.indexOf(edit);
Iterator<Body> fIter = bodys.iterator();
while(fIter.hasNext()){ // iterating through the force pulling the edit body
Body force = fIter.next(); /// ConcurrentModificationException is thrown
int placeInArrayForce = bodys.indexOf(force);
if(placeInArrayForce != placeInArrayEdit){ // making sure the 2 bodys arent the same
double fx = force.getX(), fy = force.getY();
double fMass = force.getMass();
double fMoveX = force.getMoveX(), fMoveY = force.getMoveY();
double difX = (ex-fx);
double difY = (ey-fy);
double distX = distanceP(ex, fx);
double distY = distanceP(ey, fy);
double vecX = (difX/distX);
double vecY = (difY/distY);
if(distance(fx,ex,fy,ey) <= eSize/3){ // if they are colliding
if(eMass >= fMass){
remove(edit);
edit.addMass((int)(fMass));
eIter.remove(); // problem
}
if(eMass < fMass){
remove(force);
force.addMass((int)(eMass));
fIter.remove();
}
}
double grav = (eMass/fMass);
grav -= (grav*.50);
addX -= (vecX/grav)/2; // this determines movement which means i
addY -= (vecY/grav)/2; // need to edit this with fMass
}
edit.setVelX(addX/(eMass + (eMass*.75)));
edit.setVelY(addY/(eMass + (eMass*.75)));
edit.addMoveX(edit.getVelX());
edit.addMoveY(edit.getVelY());
edit.move(edit.getMoveX(),edit.getMoveY());
}
}
}
The code above is moving the gravity wells and testing for collision. The problem is that ConcurrentModificationException is thrown where iv commented it to be thrown.
Iv spent about an hour or so looking around for a solution and nothing iv tried has worked. The code works up until the wells actually hit each other, then the error is thrown. Is there a way to avoid this error while still testing for collision like this, or is my code just too broken?
Thanks for all the help! Please let me know if you need anything clarified as this is my first question on StackOverflow
See javadoc of ArrayList:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
So, you have 2 iterators: eIter for the outer loop, and fIter for the inner loop.
When you call eIter.remove(), fIter will go bad.
When you call fIter.remove(), eIter will go bad.
(If you had called bodys.remove(index), both would go bad.)
Either way, one of the iterators will be stale, and will throw ConcurrentModificationException when you call next().
Also, when you call eIter.remove(), you don't break out of the inner loop, so you run the risk of trying to do it again in another iteration of the inner loop.
In short, you need to find another way, e.g. using indexes and get(index) calls, or something like that.

How to copy all the elements in an array list, then paste them to the array list? Example provided [duplicate]

This question already has answers here:
How to append the contents of a list at the end of the other list?
(3 answers)
Closed 8 years ago.
I want to copy all elements of ArrayList to the back of the ArrayList. For example, in my ArrayList, there are {1,2,3,4} and I want it to be like this --> {1,2,3,4,1,2,3,4}.
How do I do it?
for (int pos = 0; pos < hand.size (); pos ++)
{
hand.add (hand.get(pos));
}
This gives me an error saying out of memory...
Is there any way to make it work?
Thank you
Your loop looks roughly like:
is pos < hand.size()?
if so, add something to hand
pos++
which means that each time through the loop, pos increases, but hand.size() also increases, and so on. You get the out-of-memory error because the loop runs infinitely, and the list gets too big.
One way to do this:
int length = hand.size();
for (int pos = 0; pos < length; pos++) {
hand.add(hand.get(pos));
}
How about
hand.addAll(new ArrayList<>(hand))
Every time you add an element, the size increases, so the loop never terminates. A simple fix is to save the size in a variable before the loop:
int size = hand.size()(
for (int pos = 0; pos < size; pos ++)
{
hand.add (hand.get(pos));
}
But the simplest way to do it is:
hand.addAll(hand); // Note: It is safe to call addAll() on itself

Arrays and searching in Java [duplicate]

This question already has answers here:
Arrays.asList() not working as it should?
(12 answers)
Closed 9 years ago.
So I'm just learning about arrays in Java (interesting stuff) but I'm having some problems getting my head around the contains() method.
I tried:
Random rn = new Random();
int first = 12;
int[] tab = new int[first];
for (int i = 0; i <= first - 1; i++) {
tab[i] = rn.nextInt(10);
Which seemed to work fine for filling in my Array, but then I tried a:
System.out.println(Arrays.asList(tab).contains(9));
And no matter what, even if I fill the array manually with 9's, it'll still only print up "false".
What am I doing wrong?
Try this
Integer[] tab = new Integer[]{9};
System.out.println(java.util.Arrays.asList(tab).contains(9));
I get
true

Categories