For fun, I'm making a 2048-style combine-and-display program. Every outer loop, it adds a 2 to the 0-index of an integer array list. In an inner for-loop, it checks to see if the value of the index is the same as the value of the index above it; if it is, it doubles the value of indexi+1 and removes index i.
The output works fine for the first several loops. However, once we get to the first 128, it still works, but the next time we get a 128, it doesn't combine those to become 256, it just leaves both 128's at the end of the array.
I think the problem has to do with the code no longer recognizing 128 as being equal to 128, because it skips out of that if-statement when it should go in to it, but I'm not sure.
It currently infinitely loops; adding user interaction and quit statements will come later.
Code
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> intArray = new ArrayList();
Boolean quit = false;
while (quit == false) {
intArray.add(0, 2);
for (int i=0; i<intArray.size();i++) {
try {
if (intArray.get(i) == intArray.get(i+1)) {
intArray.set(i+1, (intArray.get(i)*2));
intArray.remove(i);
}
}
catch (IndexOutOfBoundsException e) {
}
}
for (int a : intArray) {
System.out.print(a + " ");
}
System.out.println();
}
}
}
Output
4 16 16 32 64 128
2 4 32 32 64 128
4 4 64 64 128
2 8 128 128
4 8 128 128
2 4 8 128 128
4 4 8 128 128
2 8 8 128 128
4 16 128 128
Notice that the two 64's combine to make the second 128, but then those 128's don't combine as they should.
Do integers stop comparing correctly after a certain size?